Skip to Content

PHP SDK

GitHub Repository: sunbay-nexus-sdk-php 

Official SUNBAY Nexus PHP SDK, providing complete payment integration capabilities for PHP 8.1+ applications.

Features

  • ✅ Support for PHP 8.1+
  • ✅ PHP 8.1+ named arguments for clean, readable construction
  • ✅ Fluent setter & Builder pattern also supported
  • ✅ Automatic authentication
  • ✅ Automatic retry for GET requests
  • ✅ Comprehensive exception handling
  • ✅ Type-safe enums (PHP 8.1 native enums)
  • ✅ PSR-3 logging support
  • ✅ GuzzleHttp connection pool
  • ✅ Composer installation

Installation

Current Version

Always use the latest version. Visit Packagist  for the latest version number.

Add to your composer.json:

{ "require": { "sunmi/sunbay-nexus-sdk-php": "*" } }

Then run:

composer install

Or use Composer command directly:

composer require sunmi/sunbay-nexus-sdk-php

Quick Start

1. Initialize Client

NexusClient uses an internal HTTP connection pool (GuzzleHttp). Create it once at application startup and reuse it globally — do not create a new instance for every request. Repeated creation wastes connection pool resources.

<?php require 'vendor/autoload.php'; use Sunmi\Sunbay\Nexus\NexusClient; // Create once, reuse globally $client = NexusClient::builder() ->apiKey('{YOUR_API_KEY}') // Required: API key ->baseUrl('https://open.sunbay.us') // Required: API base URL ->connectTimeout(10000) // Optional: connect timeout, default 10000ms ->readTimeout(30000) // Optional: read timeout, default 30000ms ->maxRetries(3) // Optional: GET request retries, default 3 ->maxTotal(200) // Optional: max connections in pool, default 200 ->maxPerRoute(200) // Optional: max connections per route, default 200 ->build();

We recommend tuning connectTimeout, readTimeout, maxRetries, maxTotal, and maxPerRoute based on your concurrency level and business requirements.

2. Create Payment Transaction

Important: All amount fields use the smallest currency unit (integers). For example: 100.00 USD = 10000 cents

<?php use Sunmi\Sunbay\Nexus\Model\Request\SaleRequest; use Sunmi\Sunbay\Nexus\Model\Common\SaleAmount; use Sunmi\Sunbay\Nexus\Exception\SunbayBusinessException; use Sunmi\Sunbay\Nexus\Exception\SunbayNetworkException; // Build amount (smallest currency unit) $amount = new SaleAmount( orderAmount: 10000, // 100.00 USD = 10000 cents priceCurrency: 'USD' ); // Build payment request using named arguments $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 automatically throws SunbayBusinessException when code != "0" // If code reaches here, response is guaranteed to be successful $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->getErrorCode() . " - " . $e->getMessage() . "\n"; if ($e->getTraceId()) { echo "Trace ID: " . $e->getTraceId() . "\n"; } }

API Methods

All request classes support named arguments (recommended for PHP 8.1+), fluent setters, and Builder pattern.

In-Person Payment APIs

  • sale(SaleRequest) - Payment transaction
  • auth(AuthRequest) - Pre-authorization
  • forcedAuth(ForcedAuthRequest) - Forced authorization
  • incrementalAuth(IncrementalAuthRequest) - Incremental authorization
  • postAuth(PostAuthRequest) - Post-authorization completion
  • refund(RefundRequest) - Refund
  • voidTransaction(VoidRequest) - Void transaction
  • abort(AbortRequest) - Abort transaction
  • tipAdjust(TipAdjustRequest) - Tip adjustment
  • batchQuery(BatchQueryRequest) - Query open (unsettled) batches
  • batchClose(BatchCloseRequest) - Batch settlement
  • batchCloseList(BatchCloseListRequest) - Query closed (settled) batches

Example: Pre-authorization

<?php use Sunmi\Sunbay\Nexus\Model\Request\AuthRequest; use Sunmi\Sunbay\Nexus\Model\Common\AuthAmount; $amount = new AuthAmount( orderAmount: 20000, // 200.00 USD, in cents priceCurrency: 'USD' ); $request = new AuthRequest( appId: 'app_123456', merchantId: 'mch_789012', referenceOrderId: 'AUTH' . time(), transactionRequestId: 'PAY_REQ_' . time(), amount: $amount, description: 'Hotel reservation', terminalSn: 'T1234567890' ); $response = $client->auth($request);

Online Payment APIs

  • createCheckoutSession(CreateCheckoutSessionRequest) - Create hosted checkout session
  • expireCheckoutSession(ExpireCheckoutSessionRequest) - Expire a checkout session
  • checkoutSale(CheckoutSaleRequest) - Direct payment (server-to-server)
  • onlineRefund(OnlineRefundRequest) - Online refund

Transaction Query APIs

  • query(QueryRequest) - Query transaction

Example: Query Transaction

<?php use Sunmi\Sunbay\Nexus\Model\Request\QueryRequest; $request = new QueryRequest( appId: 'app_123456', merchantId: 'mch_789012', transactionId: 'TXN20231119001' ); $response = $client->query($request);

Merchant APIs

  • merchantQuery(MerchantQueryRequest) - Retrieve merchant information
  • merchantTerminalsQuery(MerchantTerminalsQueryRequest) - List terminals bound to a merchant

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 Sunmi\Sunbay\Nexus\Exception\SunbayBusinessException; use Sunmi\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->getErrorCode() . " - " . $e->getMessage() . "\n"; if ($e->getTraceId()) { echo "Trace ID: " . $e->getTraceId() . "\n"; } }

Configuration Options

<?php use Sunmi\Sunbay\Nexus\NexusClient; $client = NexusClient::builder() ->apiKey('sk_test_xxx') ->baseUrl('https://open.sunbay.us') // Default: https://open.sunbay.us ->connectTimeout(10000) // Default: 10000ms (10 seconds) ->readTimeout(30000) // Default: 30000ms (30 seconds) ->maxRetries(3) // Default: 3 times (GET request retry) ->maxTotal(200) // Default: 200 (max connections in pool) ->maxPerRoute(200) // Default: 200 (max connections per route) ->build();

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 Sunmi\Sunbay\Nexus\NexusClient; // Create Monolog logger $logger = new Logger('nexus'); $logger->pushHandler(new StreamHandler('path/to/your.log', Logger::DEBUG)); // Create client with logger $client = NexusClient::builder() ->apiKey('sk_test_xxx') ->logger($logger) ->build();

Enums

The SDK provides type-safe PHP 8.1 native enums for common payment-related values:

Available Enums

  • PaymentCategory - Payment method category (CARD, CARD_CREDIT, CARD_DEBIT, QR_MPM, QR_CPM)
  • TransactionStatus - Transaction status codes (I=INITIAL, P=PROCESSING, S=SUCCESS, F=FAIL, C=CLOSED)
  • TransactionType - Transaction type (SALE, AUTH, FORCED_AUTH, INCREMENTAL, POST_AUTH, REFUND, VOID)
  • TransactionBatchStatus - Batch status
  • 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)
  • PrintReceiptOption - Receipt print option (NONE, MERCHANT, CUSTOMER, BOTH)
  • BatchPrintReceiptOption - Batch report print option (TOTAL, DETAIL, BOTH, NONE, AUTO)
  • SignatureEntryLocation - Signature entry location
  • EbtSubId - EBT sub ID
  • OnlineWalletPaymentMethod - Online wallet payment method
  • RelatedTransactionStatus - Related transaction status

Usage Example

<?php use Sunmi\Sunbay\Nexus\Enum\TransactionStatus; use Sunmi\Sunbay\Nexus\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'

Complete Example

<?php require 'vendor/autoload.php'; use Sunmi\Sunbay\Nexus\NexusClient; use Sunmi\Sunbay\Nexus\Model\Request\SaleRequest; use Sunmi\Sunbay\Nexus\Model\Common\SaleAmount; use Sunmi\Sunbay\Nexus\Exception\SunbayBusinessException; use Sunmi\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 $client = NexusClient::builder() ->apiKey(getenv('SUNBAY_API_KEY')) ->baseUrl('https://open.sunbay.us') ->logger($logger) ->build(); // 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"; } 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->getErrorCode() . " - " . $e->getMessage() . "\n"; if ($e->getTraceId()) { echo "Trace ID: " . $e->getTraceId() . "\n"; } }

System Requirements

  • PHP 8.1 or higher
  • Composer 2.x
  • GuzzleHttp 7.5+
  • PSR Log 3.0+

License

MIT License

Last updated on