PHP SDK

Official PHP SDK for SePay Payment Gateway. Easily integrate payments, bank transfers, VietQR, and recurring payments.


Requirements
  • PHP 7.4 or higher
  • ext-json
  • ext-curl
  • Guzzle HTTP client

Installation

Installation
composer require sepay/sepay-pg

Client Initialization

Initialization
use SePay\SePayClient;
use SePay\Builders\CheckoutBuilder;

// Initialize client
$sepay = new SePayClient(
    'SP-TEST-XXXXXXX',
    'spsk_live_xxxxxxxxxxxo99PoE7RsBpss3EFH5nV',
    SePayClient::ENVIRONMENT_SANDBOX, // or ENVIRONMENT_PRODUCTION
   []
);
  • Parameter explanation
NameTypeRequiredDescription
SP-TEST-XXXXXXX
stringRequired
Merchant ID
spsk_live_x...
stringRequired
Merchant secret key
SePayClient::ENVIRONMENT_...
stringRequired
Environment variable (ENVIRONMENT_SANDBOX or ENVIRONMENT_PRODUCTION)
[]
arrayNot required
Array of additional configuration options
  • Example of configuration options:
PHP
[
    'timeout' => 60,           // Request timeout (in seconds)
    'retry_attempts' => 5,     // Number of retry attempts when a request fails
    'retry_delay' => 2000,     // Delay between retries (in milliseconds)
    'debug' => true,           // Enable debug mode (detailed logging)
    'user_agent' => 'MyApp/1.0 SePay-PHP-SDK/1.0.0', // User agent string sent with the request
    'logger' => $customLogger, // PSR-3 compatible logger
];

Create checkout object for one-time payment

Initialize One-time Payment
$checkoutData = CheckoutBuilder::make()
    ->currency('VND')
    ->orderAmount(100000) // 100,000 VND
    ->operation('PURCHASE')
    ->orderDescription('Test payment')
    ->orderInvoiceNumber('INV_001')
    ->successUrl('https://yoursite.com/success')
    ->build();

// Create form fields with signature
$formFields = $sepay->checkout()->generateFormFields($checkoutData);
  • Field explanation
NameTypeRequiredDescription
operation
stringRequired
Transaction type, currently only supports: PURCHASE
orderInvoiceNumber
stringRequired
Order/Invoice number (unique)
orderAmount
stringRequired
Transaction amount
currency
stringRequired
Currency (e.g., VND, USD)
paymentMethod
stringNot required
Payment method: CARD, BANK_TRANSFER
orderDescription
stringNot required
Order description
customerId
stringNot required
Customer ID (if applicable)
successUrl
stringNot required
Callback URL for successful payment
errorUrl
stringNot required
Callback URL for payment errors
cancelUrl
stringNot required
Callback URL when user cancels payment
  • Generate payment form
Important note on creating HTML form and signature

If you build your own HTML form and build the signature function without following the sample code, you need to ensure the order of the fields is the same as the parameter list above so that the signing process matches SePay's side absolutely; If you swap the positions of the fields, it may lead to an incorrect signature and SePay will consider this request invalid

Payment Form
<form method="POST" action="https://pay.sepay.vn/checkout/init">
    <?php foreach ($formFields as $name => $value): ?>
        <input type="hidden" name="<?= htmlspecialchars($name) ?>" value="<?= htmlspecialchars($value) ?>">
    <?php endforeach; ?>

    <button type="submit">Pay Now</button>
</form>
Notes
Enable Debug Mode
$sepay->enableDebugMode();
Configure Retry Behavior
$sepay->setRetryAttempts(3)->setRetryDelay(1000); // milliseconds

API

The SDK provides methods for calling SePay Payment Gateway Open API.

List Orders
$orders = $sepay->orders()->list([
    'per_page' => 10,
    'order_status' => 'CAPTURED',
    'from_created_at' => '2025-01-01',
    'to_created_at' => '2025-12-31',
]);
Retrieve Order Details
$order = $sepay->orders()->retrieve('ORDER_INVOICE_NUMBER');
Void Transaction
$result = $sepay->orders()->voidTransaction('ORDER_INVOICE_NUMBER');
Note

Orders are created when the customer completes payment — not directly through the API.


Error Handling

The SDK provides multiple exception types for specific error cases.

PHP
use SePay\Exceptions\AuthenticationException;
use SePay\Exceptions\ValidationException;
use SePay\Exceptions\NotFoundException;
use SePay\Exceptions\RateLimitException;
use SePay\Exceptions\ServerException;

try {
    $order = $sepay->orders()->retrieve('ORDER_INVOICE_NUMBER');
} catch (AuthenticationException $e) {
    // Invalid credentials or signature
    echo "Authentication failed: " . $e->getMessage();
} catch (ValidationException $e) {
    // Invalid request data
    echo "Validation error: " . $e->getMessage();

    // Get field-specific errors
    if ($e->hasFieldError('amount')) {
        $errors = $e->getFieldErrors('amount');
        echo "Amount errors: " . implode(', ', $errors);
    }
} catch (NotFoundException $e) {
    // Resource not found
    echo "Not found: " . $e->getMessage();
} catch (RateLimitException $e) {
    // Rate limit exceeded
    echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
} catch (ServerException $e) {
    // Server error (5xx)
    echo "Server error: " . $e->getMessage();
}

Testing

Testing Commands
# Run all tests
composer test

# Run tests with coverage report
composer test-coverage

# Run static analysis
composer phpstan

# Fix code style
composer cs-fix

See detailed installation and usage instructions at GitHub Repository