PHP SDK
GitHub Repository: sunbay-nexus-sdk-php
Official SUNBAY Nexus PHP SDK, providing complete payment integration capabilities for PHP applications.
Features
- ✅ Support for PHP 7.4+
- ✅ Builder pattern for request construction
- ✅ Automatic authentication
- ✅ Automatic retry for GET requests
- ✅ Comprehensive exception handling
- ✅ Type-safe enums
- ✅ PSR-3 logging support
- ✅ Composer installation
Installation
Current Version: 1.0.0
Visit Packagist for the latest version.
Add to your composer.json:
{
"require": {
"sunmi/sunbay-nexus-sdk-php": "^1.0"
}
}Then run:
composer installOr use Composer command directly:
composer require sunmi/sunbay-nexus-sdk-phpQuick Start
1. Initialize Client
NexusClient is thread-safe and can be reused across multiple threads.
<?php
require 'vendor/autoload.php';
use SUNBAY\Nexus\NexusClient;
use SUNBAY\Nexus\Config\NexusConfig;
$config = new NexusConfig(
apiKey: 'sk_test_xxx',
baseUrl: 'https://open.sunbay.us'
);
$client = new NexusClient($config);2. Create Payment Transaction
Important: All amount fields use the smallest currency unit (integers). For example: 100.00 USD = 10000 cents
<?php
use SUNBAY\Nexus\Model\Request\SaleRequest;
use SUNBAY\Nexus\Model\Common\SaleAmount;
use SUNBAY\Nexus\Exception\SUNBAYBusinessException;
use SUNBAY\Nexus\Exception\SUNBAYNetworkException;
// Build amount (using smallest currency unit)
$amount = new SaleAmount(
orderAmount: 10000, // 100.00 USD = 10000 cents
priceCurrency: 'USD'
);
// Build payment request
$request = new SaleRequest(
appId: 'app_123456',
merchantId: 'mch_789012',
referenceOrderId: 'ORDER20231119001',
transactionRequestId: 'PAY_REQ_' . time(),
amount: $amount,
description: 'Product purchase',
terminalSn: 'T1234567890'
);
try {
// Execute transaction
// SDK will automatically throw SUNBAYBusinessException when code != "0"
// If code reaches here, response is guaranteed to be successful (code = "0")
$response = $client->sale($request);
echo "Transaction ID: " . $response->getTransactionId() . "\n";
echo "Reference Order ID: " . $response->getReferenceOrderId() . "\n";
} catch (SUNBAYNetworkException $e) {
// Network error
echo "Network Error: " . $e->getMessage() . "\n";
if ($e->isRetryable()) {
echo "This error is retryable\n";
}
} catch (SUNBAYBusinessException $e) {
// Business error
echo "API Error: " . $e->getCode() . " - " . $e->getMessage() . "\n";
if ($e->getTraceId()) {
echo "Trace ID: " . $e->getTraceId() . "\n";
}
}API Methods
All request classes support the Builder pattern for convenient object construction.
Transaction APIs
sale(SaleRequest)- Payment transactionauth(AuthRequest)- Pre-authorizationforcedAuth(ForcedAuthRequest)- Forced authorizationincrementalAuth(IncrementalAuthRequest)- Incremental authorizationpostAuth(PostAuthRequest)- Post-authorization completionrefund(RefundRequest)- RefundvoidTransaction(VoidRequest)- Void transactionabort(AbortRequest)- Abort transactiontipAdjust(TipAdjustRequest)- Tip adjustment
Query APIs
query(QueryRequest)- Query transaction
Settlement APIs
batchClose(BatchCloseRequest)- Batch settlement
Response Objects
All response objects inherit from BaseResponse and provide the following common methods:
getCode()- Get response codegetMessage()- Get response messagegetTraceId()- Get trace IDisSuccess()- Check if successful (code = “0”)
Important: The SDK will automatically throw SUNBAYBusinessException when the API returns a non-zero code. If your code reaches response handling without catching an exception, the response is guaranteed to be successful (code = “0”).
Transaction responses (e.g., SaleResponse, AuthResponse) also provide:
getTransactionId()- Get transaction IDgetReferenceOrderId()- Get reference order IDgetAmount()- Get amount object- etc…
Exception Handling
The SDK throws two types of exceptions:
SUNBAYNetworkException: Network-related errors (connection timeout, network errors, etc.)SUNBAYBusinessException: Business logic errors (parameter validation, API business errors, etc.)
Always catch SUNBAYNetworkException first, then SUNBAYBusinessException:
<?php
use SUNBAY\Nexus\Exception\SUNBAYBusinessException;
use SUNBAY\Nexus\Exception\SUNBAYNetworkException;
try {
$response = $client->sale($request);
// Handle successful response
echo "Transaction ID: " . $response->getTransactionId() . "\n";
} catch (SUNBAYNetworkException $e) {
// Network exception (e.g., connection timeout, network error)
echo "Network Error: " . $e->getMessage() . "\n";
if ($e->isRetryable()) {
// Can retry
echo "This error is retryable\n";
}
} catch (SUNBAYBusinessException $e) {
// Business exception (e.g., insufficient funds, parameter error)
echo "API Error: " . $e->getCode() . " - " . $e->getMessage() . "\n";
if ($e->getTraceId()) {
echo "Trace ID: " . $e->getTraceId() . "\n";
}
// Handle based on error code
switch ($e->getCode()) {
case 'INSUFFICIENT_FUNDS':
// Handle insufficient funds
break;
case 'INVALID_CARD':
// Handle invalid card
break;
default:
// Handle other errors
break;
}
}Configuration Options
<?php
use SUNBAY\Nexus\Config\NexusConfig;
$config = new NexusConfig(
apiKey: 'sk_test_xxx',
baseUrl: 'https://open.sunbay.us', // Default: https://open.sunbay.us
timeout: 30, // Default: 30 seconds
maxRetries: 3, // Default: 3 times
connectTimeout: 10 // Default: 10 seconds
);
$client = new NexusClient($config);Logging
The SDK supports PSR-3 compatible loggers for logging HTTP requests and responses. You can use any PSR-3 compatible logging library:
Using Monolog
<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use SUNBAY\Nexus\Config\NexusConfig;
use SUNBAY\Nexus\NexusClient;
// Create Monolog logger
$logger = new Logger('nexus');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::DEBUG));
// Create config with logger
$config = new NexusConfig(
apiKey: 'sk_test_xxx',
logger: $logger
);
$client = new NexusClient($config);Using Other PSR-3 Logging Libraries
<?php
use YourLogger\Logger; // Any PSR-3 compatible logger
$logger = new Logger();
$config = new NexusConfig(
apiKey: 'sk_test_xxx',
logger: $logger
);
$client = new NexusClient($config);Enums
The SDK provides type-safe enums for common payment-related values. These enums help prevent invalid values and provide better IDE support:
Available Enums
PaymentCategory- Payment method category (CARD, CARD_CREDIT, CARD_DEBIT, QR_MPM, QR_CPM)TransactionStatus- Transaction status codes returned by API (I=INITIAL, P=PROCESSING, S=SUCCESS, F=FAIL, C=CLOSED)TransactionType- Transaction type (SALE, AUTH, FORCED_AUTH, INCREMENTAL, POST_AUTH, REFUND, VOID)CardNetworkType- Card network type (CREDIT, DEBIT, EBT, EGC, UNKNOWN)EntryMode- Card entry mode (MANUAL, SWIPE, FALLBACK_SWIPE, CONTACT, CONTACTLESS)AuthenticationMethod- Authentication method (NOT_AUTHENTICATED, PIN, OFFLINE_PIN, BY_PASS, SIGNATURE)
Usage Example
<?php
use SUNBAY\Nexus\Model\Enum\TransactionStatus;
use SUNBAY\Nexus\Model\Enum\CardNetworkType;
$response = $client->query($request);
// Use enum comparison
if ($response->getTransactionStatus() === TransactionStatus::SUCCESS) {
echo "Transaction successful\n";
}
// Get enum value
echo $response->getTransactionStatus()->value; // 'S'
// Check card type
if ($response->getCardNetworkType() === CardNetworkType::CREDIT) {
echo "Credit card transaction\n";
}Note:
- Enums provide type safety and IDE auto-completion
- Response fields are automatically converted to enum types
- Use
->valueto get the raw string value
Complete Example
<?php
require 'vendor/autoload.php';
use SUNBAY\Nexus\NexusClient;
use SUNBAY\Nexus\Config\NexusConfig;
use SUNBAY\Nexus\Model\Request\SaleRequest;
use SUNBAY\Nexus\Model\Common\SaleAmount;
use SUNBAY\Nexus\Exception\SUNBAYBusinessException;
use SUNBAY\Nexus\Exception\SUNBAYNetworkException;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// Configure logging (optional)
$logger = new Logger('nexus');
$logger->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG));
// Initialize client
$config = new NexusConfig(
apiKey: getenv('SUNBAY_API_KEY'),
baseUrl: 'https://open.sunbay.us',
timeout: 30,
logger: $logger
);
$client = new NexusClient($config);
// Create payment request
$amount = new SaleAmount(
orderAmount: 10000, // 100.00 USD = 10000 cents
priceCurrency: 'USD'
);
$request = new SaleRequest(
appId: 'app_123456',
merchantId: 'mch_789012',
referenceOrderId: 'ORDER' . time(),
transactionRequestId: 'PAY_REQ_' . uniqid(),
amount: $amount,
description: 'Product purchase',
terminalSn: 'T1234567890'
);
try {
// Execute transaction
$response = $client->sale($request);
// Handle successful response
echo "Transaction successful!\n";
echo "Transaction ID: " . $response->getTransactionId() . "\n";
echo "Reference Order ID: " . $response->getReferenceOrderId() . "\n";
echo "Amount: $" . number_format($response->getAmount()->getOrderAmount() / 100, 2) . "\n";
} catch (SUNBAYNetworkException $e) {
// Network error
echo "Network error: " . $e->getMessage() . "\n";
if ($e->isRetryable()) {
echo "This error is retryable, you can retry the request\n";
}
} catch (SUNBAYBusinessException $e) {
// Business error
echo "Business error: " . $e->getCode() . " - " . $e->getMessage() . "\n";
if ($e->getTraceId()) {
echo "Trace ID: " . $e->getTraceId() . "\n";
}
}System Requirements
- PHP 7.4 or higher
- Composer 2.x
- cURL extension
- JSON extension
Related Links
License
MIT License