PHP code example of sunmi / sunbay-nexus-sdk-php

1. Go to this page and download the library: Download sunmi/sunbay-nexus-sdk-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sunmi / sunbay-nexus-sdk-php example snippets



use Sunmi\Sunbay\Nexus\NexusClient;

$client = NexusClient::builder()
    ->apiKey('your_api_key_here')
    ->baseUrl('https://open.sunbay.us')      // optional, defaults to https://open.sunbay.us
    ->connectTimeout(10000)                   // optional, default 10000ms
    ->readTimeout(30000)                      // optional, default 30000ms
    ->maxRetries(3)                           // optional, GET retry count, default 3
    ->maxTotal(200)                           // optional, max pool connections, default 200
    ->maxPerRoute(200)                        // optional, max connections per host, default 200
    ->build();


use Sunmi\Sunbay\Nexus\Model\Common\SaleAmount;
use Sunmi\Sunbay\Nexus\Model\Request\SaleRequest;
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 sale 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 automatically throws SunbayBusinessException when code != "0"
    // If we reach here, the response is guaranteed 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";
    }
}

try {
    $response = $client->sale($request);
    // Handle success
} catch (SunbayNetworkException $e) {
    // Network exception (e.g., connection timeout, network error)
    echo "Network Error: " . $e->getMessage() . "\n";
    if ($e->isRetryable()) {
        // Can retry
    }
} catch (SunbayBusinessException $e) {
    // Business exception (e.g., insufficient funds, parameter error)
    echo "API Error: " . $e->getErrorCode() . " - " . $e->getMessage() . "\n";
    if ($e->getTraceId() !== null) {
        echo "Trace ID: " . $e->getTraceId() . "\n";
    }
}

use Psr\Log\LoggerInterface;

$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 retries for GET requests
    ->maxTotal(200)                       // Default: 200 (max total connections in pool)
    ->maxPerRoute(200)                    // Default: 200 (max connections per host)
    ->logger($logger)                     // Optional: PSR-3 logger for request/response logging
    ->build();

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('sunbay-sdk');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::INFO));

$client = NexusClient::builder()
    ->apiKey('sk_test_xxx')
    ->logger($logger)  // Optional: omit to disable logging
    ->build();

use Sunmi\Sunbay\Nexus\Enum\PaymentCategory;
use Sunmi\Sunbay\Nexus\Enum\TransactionStatus;
use Sunmi\Sunbay\Nexus\Model\Common\PaymentMethodInfo;
use Sunmi\Sunbay\Nexus\Model\Response\QueryResponse;

// Use enum for type safety when building requests
$paymentMethod = new PaymentMethodInfo(
    category: PaymentCategory::CARD->value
);

// When reading responses, validate enum values
$queryResponse = $client->query($request);
if ($queryResponse->getTransactionStatus() !== null) {
    $statusCode = $queryResponse->getTransactionStatus();
    // Validate against enum (API returns code like "I", "P", "S", "F", "C")
    $validStatuses = array_map(fn($case) => $case->value, TransactionStatus::cases());
    if (in_array($statusCode, $validStatuses)) {
        // Status is valid
    }
}

// Enums work seamlessly with JSON serialization
$json = json_encode(['category' => PaymentCategory::QR_MPM->value]);
// Output: {"category":"QR-MPM"}