chainberry/external-sdk-php
最新稳定版本:2.0.3
Composer 安装命令:
composer require chainberry/external-sdk-php
包简介
Chainberry PHP SDK
README 文档
README
For full details on how to use the ChainBerry SDK, check out the official documentation here: https://chainberry-docs.notaku.site. Please note that the docs are still a work in progress, and we're actively updating them - so feel free to reach out at support@chianberry.com if something's missing or unclear!
Overview
This PHP SDK provides easy integration with the Chainberry API for deposits, crypto operations, and other API features. It includes both low-level API access and a high-level BerrySdk wrapper for simplified usage.
Features
- API Setup & Configuration: Easy initialization with environment variables or configuration arrays
- Deposit Management: Create and retrieve deposits with automatic signature generation
- Crypto Operations: Sign payloads and verify signatures using RSA-SHA256
- Dual API Coverage: Target both legacy V1 and modern V2 endpoints from one SDK
- Error Handling: Comprehensive error classes for different types of errors
- Retry Logic: Built-in retry mechanisms with exponential backoff
- Validation: Input validation with customizable rules
- Logging: Configurable logging system
- OAuth Authentication: Automatic OAuth token management
Installation & Usage
Requirements
PHP 8.1 and later.
Composer
To install the bindings via Composer, add the following to composer.json:
{
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
"chainberry/external-sdk-php": "dev-main"
}
}
Then run composer install
Manual Installation
Download the files and include autoload.php:
<?php require_once('/path/to/OpenAPIClient-php/vendor/autoload.php');
Quick Start with BerrySdk
Configuration
Environment Variables
Set the following environment variables:
export CB_API_ENVIRONMENT=staging # or production, local export CB_API_VERSION=v2 # or v1 (defaults to v1 if not set) export CB_API_CLIENT_ID=your_client_id export CB_API_CLIENT_SECRET=your_client_secret export CB_API_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
Configuration Array
Alternatively, you can pass configuration directly:
$config = [ 'environment' => 'staging', // or 'production', 'local' 'apiVersion' => 'v2', // or 'v1' (defaults to 'v1' if not set) 'clientId' => 'your_client_id', 'clientSecret' => 'your_client_secret', 'privateKey' => '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----' ];
Environment and API Version Matrix (V1 vs V2)
The SDK uses two separate configuration values:
- Environment (
CB_API_ENVIRONMENTor$config['environment']): The deployment environment (staging, production, or local) - API Version (
CB_API_VERSIONor$config['apiVersion']): The API version to use (v1 or v2)
Both values are combined to determine the base URL. The API version defaults to v1 if not specified.
| Environment | Constant | API Version | Base URL | Typical use case |
|---|---|---|---|---|
staging |
Environment::STAGING |
v1 |
https://api-stg.chainberry.com/api/v1 |
Legacy flows in staging |
staging |
Environment::STAGING |
v2 |
https://api-stg.chainberry.com/api/v2 |
New V2 flows in staging |
production |
Environment::PRODUCTION |
v1 |
https://api.chainberry.com/api/v1 |
Legacy flows in production |
production |
Environment::PRODUCTION |
v2 |
https://api.chainberry.com/api/v2 |
New V2 flows in production |
local |
Environment::LOCAL |
v1 |
http://192.168.0.226:3001/api/v1 |
Local V1 gateway |
local |
Environment::LOCAL |
v2 |
http://192.168.0.226:3001/api/v2 |
Local V2 gateway |
You can call both V1 and V2 helpers from the same process, but make sure the
CB_API_VERSION(or$config['apiVersion']) matches the endpoints you want to invoke. Mixing V1 helpers with a V2 API version (or vice versa) will result in authentication failures.
Initialize the SDK (shared bootstrap)
<?php require_once 'vendor/autoload.php'; use OpenAPI\Client\BerrySdk; // Initialize with environment variables BerrySdk::init(); // Or initialize with configuration array BerrySdk::init($config);
V2 Quick Start Examples
Make sure CB_API_VERSION (or $config['apiVersion']) is set to v2 before calling the helpers in this section.
<?php use OpenAPI\Client\BerrySdk; BerrySdk::init(); // Create a deposit (V2) $deposit = BerrySdk::createDepositV2([ 'amount' => '100.00', 'currency' => 'USDC', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'network' => 'ETH', ]); // Create a withdrawal (V2) $withdraw = BerrySdk::createWithdrawV2([ 'amount' => '50.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'address' => '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', 'network' => 'TRX', ]); // Fetch existing records (V2) $depositInfo = BerrySdk::getDepositV2('payment_id'); $withdrawInfo = BerrySdk::getWithdrawV2('payment_id');
V1 Quick Start Examples (Legacy)
If you still rely on the original contracts, set CB_API_VERSION to v1 (or omit it, as v1 is the default).
<?php use OpenAPI\Client\BerrySdk; BerrySdk::init(); // Create a deposit (V1) $deposit = BerrySdk::createDeposit([ 'amount' => '100.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'tradingAccountLogin' => 'user123', 'address' => '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', ]); // Create a withdrawal (V1) $withdraw = BerrySdk::createWithdraw([ 'amount' => '50.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'tradingAccountLogin' => 'user123', 'address' => '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', ]); // Fetch existing records (V1) $depositInfo = BerrySdk::getDeposit('payment_id'); $withdrawInfo = BerrySdk::getWithdraw('payment_id');
Crypto Operations
<?php use OpenAPI\Client\BerrySdk; // Initialize the SDK BerrySdk::init(); // Sign a payload $payload = [ 'amount' => '100.00', 'currency' => 'USDT', 'timestamp' => time() ]; $privateKey = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----'; $signedPayload = BerrySdk::signPayload($payload, $privateKey); // Verify a signature $publicKey = '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----'; $isValid = BerrySdk::verifySignature($signedPayload, $publicKey); echo "Signature valid: " . ($isValid ? 'Yes' : 'No');
Advanced Usage
Using the API Setup Directly
<?php use OpenAPI\Client\ApiSetup; use OpenAPI\Client\Environment; // Get API setup instance $apiSetup = ApiSetup::getInstance(); // Initialize with configuration $apiSetup->init([ 'environment' => Environment::STAGING, 'apiVersion' => 'v2', // or 'v1' 'clientId' => 'your_client_id', 'clientSecret' => 'your_client_secret', 'privateKey' => 'your_private_key' ]); // Get API instances $assetApi = $apiSetup->getAssetApi(); $depositsApi = $apiSetup->getDepositsApi(); $oauthApi = $apiSetup->getOauthApi(); // Use APIs directly $supportedAssets = $assetApi->assetV2ControllerGetSupportedAssetsV2();
Using the Deposit Service
<?php use OpenAPI\Client\Services\DepositService; // Initialize the SDK first BerrySdk::init(); // Create deposit service $depositService = new DepositService(); // Get signed deposit request $signedRequest = $depositService->getSignedDepositRequest([ 'amount' => '100.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'network' => 'ETH' ]); // Create deposit $deposit = $depositService->createDeposit([ 'amount' => '100.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'network' => 'ETH' ]); // Get deposit with retry logic $depositInfo = $depositService->getDeposit('payment_id', 3); // 3 retries
Using the Withdraw Service
<?php use OpenAPI\Client\Services\WithdrawService; // Initialize the SDK first BerrySdk::init(); // Create withdraw service $withdrawService = new WithdrawService(); // Get signed withdrawal request $signedRequest = $withdrawService->getSignedWithdrawRequest([ 'amount' => '50.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'address' => '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', 'network' => 'TRX' ]); // Create withdrawal $withdraw = $withdrawService->createWithdraw([ 'amount' => '50.00', 'currency' => 'USDT', 'callbackUrl' => 'https://your-callback-url.com/webhook', 'partnerUserID' => 'user123', 'address' => '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6', 'network' => 'TRX' ]); // Get withdrawal with retry logic $withdrawInfo = $withdrawService->getWithdraw('payment_id', 3); // 3 retries
Error Handling
<?php use OpenAPI\Client\BerrySdk; use OpenAPI\Client\Errors\BadRequestError; use OpenAPI\Client\Errors\UnauthorizedError; use OpenAPI\Client\Errors\ConfigurationError; use OpenAPI\Client\Errors\NetworkError; try { BerrySdk::init(); $deposit = BerrySdk::createDeposit($params); } catch (ConfigurationError $e) { echo "Configuration error: " . $e->getMessage(); } catch (BadRequestError $e) { echo "Bad request: " . $e->getMessage(); } catch (UnauthorizedError $e) { echo "Unauthorized: " . $e->getMessage(); } catch (NetworkError $e) { echo "Network error: " . $e->getMessage(); } catch (Exception $e) { echo "Unexpected error: " . $e->getMessage(); }
Validation
<?php use OpenAPI\Client\Utils\Validators; use OpenAPI\Client\Utils\ValidationRules; // Use pre-built validators $emailValidator = Validators::email(); $result = $emailValidator->validate('test@example.com'); if (!$result->isValid) { echo "Validation errors: " . implode(', ', $result->errors); } // Create custom validator $customValidator = new Validator(); $customValidator ->addRule(ValidationRules::required("Field is required")) ->addRule(ValidationRules::minLength(5, "Minimum 5 characters")) ->addRule(ValidationRules::pattern('/^[A-Z]+$/', "Only uppercase letters")); $result = $customValidator->validate('HELLO'); if (!$result->isValid) { echo "Validation errors: " . implode(', ', $result->errors); }
Retry Logic
<?php use OpenAPI\Client\Utils\Retry; use OpenAPI\Client\Utils\RetryOptions; // Use retry with default options $result = Retry::withRetry(function() { // Your operation here return someApiCall(); }); // Use retry with custom options $options = new RetryOptions([ 'maxAttempts' => 5, 'baseDelay' => 2000, 'maxDelay' => 30000, 'backoffMultiplier' => 1.5 ]); $result = Retry::withRetry(function() { return someApiCall(); }, $options);
Logging
<?php use OpenAPI\Client\BerrySdk; use OpenAPI\Client\Utils\Logger; use OpenAPI\Client\Utils\LogLevel; // Get logger instance $logger = BerrySdk::getLogger(); // Configure logger $logger->setLevel(LogLevel::DEBUG); $logger->setPrefix('[MyApp]'); // Log messages $logger->info('Application started'); $logger->debug('Debug information', ['data' => $someData]); $logger->warn('Warning message'); $logger->error('Error occurred', ['error' => $error]);
Low-Level API Usage
For direct API access without the BerrySdk wrapper, you can use the generated API classes directly:
<?php require_once(__DIR__ . '/vendor/autoload.php'); $apiInstance = new OpenAPI\Client\Api\AssetApi( // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. // This is optional, `GuzzleHttp\Client` will be used as default. new GuzzleHttp\Client() ); try { $result = $apiInstance->assetV2ControllerGetSupportedAssetsV2(); print_r($result); } catch (Exception $e) { echo 'Exception when calling AssetApi->assetV2ControllerGetSupportedAssetsV2: ', $e->getMessage(), PHP_EOL; }
API Endpoints
All URIs are relative to http://localhost:3001/api/v1
| Class | Method | HTTP request | Description |
|---|---|---|---|
| AssetApi | assetV2ControllerGetSupportedAssetsV2 | GET /asset | |
| ConvertApi | autoConversionV2ControllerAutoConversionV2 | POST /convert | |
| BinanceApi | binanceControllerExecuteTradingWorkflow | POST /binance/workflow/execute | |
| BinanceApi | binanceControllerGetAveragePrice | GET /binance/average-price/{symbol} | |
| BinanceApi | binanceControllerGetAveragePrices | GET /binance/average-prices | |
| BinanceApi | binanceControllerGetCommonAveragePrices | GET /binance/common-average-prices | |
| BinanceApi | binanceControllerGetWithdrawFee | GET /binance/withdraw-fee/{currency} | |
| BinanceApi | binanceControllerValidateSymbol | GET /binance/validate-symbol/{symbol} | |
| BinanceApi | binanceControllerWithdrawToFireblocks | POST /binance/withdraw | |
| DepositsApi | depositV2ControllerCreateDepositV2 | POST /deposits | |
| DepositsApi | depositV2ControllerGetDepositV2 | GET /deposits/{paymentId} | |
| DepositsApi | depositV2ControllerGetDepositPaymentV2 | GET /deposits/payments/{paymentId} | |
| DepositsApi | depositControllerSetupSupportingAssets | GET /deposits/setup-supporting-assets | |
| DepositsApi | depositControllerSyncUpWithFireblocks | GET /deposits/sync-up-with-fireblocks | |
| HealthApi | appControllerHealth | GET /health | Get the health of the API |
| KytApi | kytControllerHandleMonitorNotification | POST /kyt | Process KYT monitor notification |
| OauthApi | oAuthV2ControllerTokenV2 | POST /oauth/token | |
| PartnersApi | partnerControllerGetCurrentPartner | GET /partners/me | |
| PublicKeyApi | publicKeyControllerDownloadPublicKey | GET /public-key | |
| SideshiftApi | sideShiftControllerCreateVariableShift | POST /sideshift/shifts/variable | |
| SideshiftApi | sideShiftControllerGetPair | GET /sideshift/pair/{from}/{to} | |
| SideshiftApi | sideShiftControllerGetShift | GET /sideshift/shifts/{shiftId} | |
| TestApi | testV2ControllerInitParamsV2 | POST /test/init-params | Test the init params with JWT token and apiToken |
| TestApi | testControllerTestCallback | POST /test/callback | |
| TestApi | testControllerTestJwt | GET /test/jwt | Test the API with JWT token |
| TestApi | testControllerTestSignatureGeneration | POST /test/signature-generation | Test the API with signature generation |
| TestApi | testControllerTestSignatureVerificationMiddleware | POST /test/signature-verification | Test the API with signature verification middleware. Requires apiToken in body. ApiToken is partnerId |
| WebhookApi | webhookControllerHandleWebhook | POST /webhook | |
| WithdrawApi | withdrawV2ControllerCreateWithdrawV2 | POST /withdraw | |
| WithdrawApi | withdrawV2ControllerGetWithdrawV2 | GET /withdraw/{paymentId} |
Models
- AutoConversionRequestV2Dto
- AutoConversionResponseV2Dto
- BinanceControllerGetAveragePrice200Response
- BinanceControllerGetWithdrawFee200Response
- BinanceControllerValidateSymbol200Response
- BinanceOrderResponseDto
- BinanceWithdrawRequestDto
- BinanceWithdrawResponseDto
- BinanceWorkflowConfigDto
- BinanceWorkflowResponseDto
- DepositRequestV2Dto
- DepositResponseV2Dto
- PaymentResponseV2Dto
- PaymentResponseV2DtoCryptoTransactionInfoInner
- WithdrawRequestV2Dto
- WithdrawResponseV2Dto
- WithdrawV2Dto
- WithdrawV2DtoCryptoTransactionInfoInner
- InitTestParamsDto
- KytMonitorNotificationDto
- PartnerDto
- SideShiftPairResponseDto
- SideShiftShiftDepositDto
- SideShiftShiftResponseDto
- SideShiftVariableShiftRequestDto
- SideShiftVariableShiftResponseDto
- SuccessDto
- SupportedAssetDto
- TokenRequestDto
- TokenResponseDto
API Reference
BerrySdk Class
Static Methods
init(?array $config = null): ApiSetup- Initialize the SDKgetApi(): ApiSetup- Get the API setup instancegetLogger(): Logger- Get the logger instancecreateDeposit(array $params): \OpenAPI\Client\Model\DepositResponseV2Dto- Create a depositgetDeposit(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\PaymentResponseV2Dto- Get deposit informationcreateWithdraw(array $params): \OpenAPI\Client\Model\WithdrawResponseV2Dto- Create a withdrawalgetWithdraw(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\WithdrawV2Dto- Get withdrawal informationsignPayload(array $payload, string $privateKey): array- Sign a payloadverifySignature(array $dataWithSignature, string $publicKey): bool- Verify a signaturereset(): void- Reset the SDK instance
ApiSetup Class
Methods
getInstance(): ApiSetup- Get singleton instanceinit(?array $config = null): ApiSetup- Initialize with configurationgetAccessToken(): ?string- Get OAuth access tokenensureAccessToken(): string- Ensure access token is availablegetConfig(): ?ExternalApiConfig- Get current configurationgetAssetApi(): AssetApi- Get Asset API instancegetAutoConversionApi(): ConvertApi- Get Auto Conversion API instancegetDepositsApi(): DepositsApi- Get Deposits API instancegetWithdrawApi(): WithdrawApi- Get Withdraw API instancegetOauthApi(): OauthApi- Get OAuth API instancegetTestApi(): TestApi- Get Test API instance
DepositService Class
Methods
getSignedDepositRequest(array $params): \OpenAPI\Client\Model\DepositRequestV2Dto- Get signed deposit requestcreateDeposit(array $params): \OpenAPI\Client\Model\DepositResponseV2Dto- Create and submit depositgetDeposit(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\PaymentResponseV2Dto- Get deposit with retrygetDepositWithEnvAuth(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\PaymentResponseV2Dto- Get deposit with env auth
WithdrawService Class
Methods
getSignedWithdrawRequest(array $params): \OpenAPI\Client\Model\WithdrawRequestV2Dto- Get signed withdrawal requestcreateWithdraw(array $params): \OpenAPI\Client\Model\WithdrawResponseV2Dto- Create and submit withdrawalgetWithdraw(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\WithdrawV2Dto- Get withdrawal with retrygetWithdrawWithEnvAuth(string $paymentId, int $maxRetries = 2): \OpenAPI\Client\Model\WithdrawV2Dto- Get withdrawal with env auth
CryptoUtils Class
Static Methods
signPayload(array $payload, string $privateKey): array- Sign payload with private keyverifySignature(array $dataWithSignature, string $publicKey): bool- Verify signature
Error Classes
BerrySdkError- Base error classConfigurationError- Configuration related errorsAuthenticationError- Authentication related errorsApiError- API request related errorsValidationError- Validation related errorsCryptoError- Crypto/signature related errorsNetworkError- Network/connection related errorsRateLimitError- Rate limiting errorsBadRequestError- Bad request errorsUnauthorizedError- Unauthorized errors
Authorization
Authentication schemes defined for the API:
bearer
- Type: Bearer authentication (JWT)
Examples
See the examples/ directory for complete working examples.
Tests
To run the tests, use:
composer install vendor/bin/phpunit
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
This project is licensed under the MIT License.
About this package
This PHP package is automatically generated by the OpenAPI Generator project:
- API version:
1.15- Generator version:
7.14.0
- Generator version:
- Build package:
org.openapitools.codegen.languages.PhpClientCodegen
统计信息
- 总下载量: 36
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: unlicense
- 更新时间: 2025-08-04