Go SDK
GitHub Repository: sunbay-nexus-sdk-go
Official SUNBAY Nexus Go SDK, providing complete payment integration capabilities for Go applications.
Features
- ✅ Clean Go-style API
- ✅ Complete type definitions
- ✅ Automatic authentication
- ✅ Automatic retry for GET requests
- ✅ Comprehensive error handling
- ✅ Connection pool management
- ✅ Support for custom logging
- ✅ Context support
Installation
go get github.com/sunbay-developer/sunbay-nexus-sdk-goQuick Start
1. Initialize Client
NexusClient is thread-safe and can be reused across multiple goroutines.
package main
import (
"context"
"fmt"
"log"
nexus "github.com/sunbay-developer/sunbay-nexus-sdk-go"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/errors"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/model/request"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/model/common"
)
func main() {
// Create NexusClient using Config
config := &nexus.Config{
APIKey: "your-api-key",
BaseURL: "https://open.sunbay.us",
}
client, err := nexus.NewNexusClient(config)
if err != nil {
log.Fatal(err)
}
// Use client...
}2. Create Payment Transaction
Important: All amount fields use cents (smallest currency unit). For example: 100.00 USD = 10000 cents
// Build request
// Note: All amounts use cents (e.g., 100.00 USD = 10000 cents)
orderAmount := int64(10000)
req := &request.SaleRequest{
AppID: "app_123456",
MerchantID: "mch_789012",
ReferenceOrderID: "ORDER20231119001",
TransactionRequestID: "PAY_REQ_1234567890",
Amount: &common.SaleAmount{
OrderAmount: &orderAmount,
PriceCurrency: "USD",
},
Description: "Product purchase",
TerminalSN: "T1234567890",
}
// Execute transaction
ctx := context.Background()
resp, err := client.Sale(ctx, req)
if err != nil {
// Error handling
if bizErr, ok := err.(*errors.BusinessError); ok {
log.Printf("Business error: code=%s, msg=%s, traceID=%s",
bizErr.Code(), bizErr.Message(), bizErr.TraceID())
} else if netErr, ok := err.(*errors.NetworkError); ok {
log.Printf("Network error: %v (retryable: %v)", netErr, netErr.IsRetryable())
}
return
}
// Handle response (if no error, response is successful)
fmt.Printf("Transaction ID: %s\n", resp.TransactionID)3. Advanced Configuration
config := &nexus.Config{
APIKey: "your-api-key",
BaseURL: "https://open.sunbay.us",
Timeout: 30 * time.Second, // Default: 30 seconds
MaxRetries: 3, // Default: 3 times
MaxIdleConns: 100, // Default: 100
MaxIdleConnsPerHost: 10, // Default: 10
IdleConnTimeout: 90 * time.Second, // Default: 90 seconds
}
client, err := nexus.NewNexusClient(config)
if err != nil {
log.Fatal(err)
}4. Custom Logging
The SDK supports custom loggers. If no logger is provided, a default console logger will be used.
import (
"log"
"os"
nexus "github.com/sunbay-developer/sunbay-nexus-sdk-go"
)
// Create custom logger
logger := log.New(os.Stdout, "[NEXUS] ", log.LstdFlags)
config := &nexus.Config{
APIKey: "your-api-key",
BaseURL: "https://open.sunbay.us",
Logger: logger,
}
client, err := nexus.NewNexusClient(config)API Methods
Transaction APIs
Sale(ctx, req)- Payment transactionAuth(ctx, req)- Pre-authorization transactionForcedAuth(ctx, req)- Forced authorization transactionIncrementalAuth(ctx, req)- Incremental authorization transactionPostAuth(ctx, req)- Post-authorization completion transactionRefund(ctx, req)- Refund transactionVoid(ctx, req)- Void transactionAbort(ctx, req)- Abort transactionTipAdjust(ctx, req)- Tip adjustment transactionBatchClose(ctx, req)- Batch settlement transaction
Query APIs
Query(ctx, req)- Query transaction
Amount Format
Important: All amount fields in the SDK use cents (smallest currency unit), not currency units.
For example:
- 100.00 USD = 10000 cents
- 50.50 EUR = 5050 cents
- 100 JPY = 100 (Japanese Yen has no decimal places, use the original value directly)
When building requests, always convert currency amounts to cents:
// ❌ Wrong - Don't use currency units
orderAmount := int64(100) // This represents 1.00 USD, not 100.00 USD
// ✅ Correct - Use cents
orderAmount := int64(10000) // 100.00 USD = 10000 cents
req := &request.SaleRequest{
Amount: &common.SaleAmount{
OrderAmount: &orderAmount,
PriceCurrency: "USD",
},
// ... other fields
}Amounts in responses are also returned in cents, so you may need to convert them back to currency units for display:
resp, err := client.Sale(ctx, req)
if err != nil {
// Handle error
}
// Convert cents to currency units for display
amountInDollars := float64(resp.Amount.OrderAmount) / 100.0
fmt.Printf("Amount: $%.2f\n", amountInDollars)Error Handling
The SDK returns two types of errors:
BusinessError: Business logic errors (parameter validation, API business errors, etc.)NetworkError: Network-related errors (connection timeout, network errors, etc.)
Always check the error type:
resp, err := client.Sale(ctx, req)
if err != nil {
// Type assertion to check error type
if bizErr, ok := err.(*errors.BusinessError); ok {
// Business error
log.Printf("Business error: code=%s, msg=%s, traceID=%s",
bizErr.Code(), bizErr.Message(), bizErr.TraceID())
// Handle based on error code
switch bizErr.Code() {
case "INSUFFICIENT_FUNDS":
// Handle insufficient funds
case "INVALID_CARD":
// Handle invalid card
default:
// Handle other business errors
}
} else if netErr, ok := err.(*errors.NetworkError); ok {
// Network error
log.Printf("Network error: %v", netErr)
if netErr.IsRetryable() {
// Can retry
log.Println("This error is retryable")
}
} else {
// Other errors
log.Printf("Unexpected error: %v", err)
}
return
}
// Handle successful response
fmt.Printf("Transaction ID: %s\n", resp.TransactionID)Configuration Options
config := &nexus.Config{
APIKey: "your-api-key", // Required
BaseURL: "https://open.sunbay.us", // Optional, default: https://open.sunbay.us
Timeout: 30 * time.Second, // Optional, default: 30 seconds
MaxRetries: 3, // Optional, default: 3 times
MaxIdleConns: 100, // Optional, default: 100
MaxIdleConnsPerHost: 10, // Optional, default: 10
IdleConnTimeout: 90 * time.Second, // Optional, default: 90 seconds
Logger: customLogger, // Optional, default: console logger
}Connection Pool Configuration
- MaxIdleConns: Maximum idle connections across all hosts in the pool (default: 100)
- MaxIdleConnsPerHost: Maximum idle connections per host (default: 10)
- IdleConnTimeout: Maximum time an idle connection remains idle before closing (default: 90 seconds)
These settings help optimize performance in high-concurrency scenarios.
Complete Example
package main
import (
"context"
"fmt"
"log"
"time"
nexus "github.com/sunbay-developer/sunbay-nexus-sdk-go"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/errors"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/model/request"
"github.com/sunbay-developer/sunbay-nexus-sdk-go/model/common"
)
func main() {
// Initialize client
config := &nexus.Config{
APIKey: "your-api-key",
BaseURL: "https://open.sunbay.us",
Timeout: 30 * time.Second,
}
client, err := nexus.NewNexusClient(config)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Create payment request
orderAmount := int64(10000) // 100.00 USD = 10000 cents
req := &request.SaleRequest{
AppID: "app_123456",
MerchantID: "mch_789012",
ReferenceOrderID: "ORDER20231119001",
TransactionRequestID: fmt.Sprintf("PAY_REQ_%d", time.Now().Unix()),
Amount: &common.SaleAmount{
OrderAmount: &orderAmount,
PriceCurrency: "USD",
},
Description: "Product purchase",
TerminalSN: "T1234567890",
}
// Execute transaction
ctx := context.Background()
resp, err := client.Sale(ctx, req)
if err != nil {
if bizErr, ok := err.(*errors.BusinessError); ok {
log.Printf("Business error: %s - %s (TraceID: %s)",
bizErr.Code(), bizErr.Message(), bizErr.TraceID())
} else if netErr, ok := err.(*errors.NetworkError); ok {
log.Printf("Network error: %v (Retryable: %v)",
netErr, netErr.IsRetryable())
} else {
log.Printf("Unexpected error: %v", err)
}
return
}
// Handle successful response
fmt.Printf("Transaction successful!\n")
fmt.Printf("Transaction ID: %s\n", resp.TransactionID)
fmt.Printf("Reference Order ID: %s\n", resp.ReferenceOrderID)
fmt.Printf("Amount: $%.2f\n", float64(resp.Amount.OrderAmount)/100.0)
}System Requirements
- Go 1.18 or higher
Related Links
License
MIT License