Server-side PHP SDK for integrating Nylon Pay payment operations into your application.
composer require nile-squad/nylonpay-phpRequires PHP 8.1+ with ext-curl, ext-json, ext-openssl, and ext-mbstring.
<?php
require 'vendor/autoload.php';
use NileSquad\NylonPay\SdkError;
use function NileSquad\NylonPay\createNylonPay;
$nylon = createNylonPay([
'apiKey' => 'npk_test_...',
'apiSecret' => 'nps_test_...',
'onError' => function (SdkError $error): void {
if ($error->reason === 'SERVICES_DOWN') {
error_log('Pause payment attempts: ' . $error->message);
}
},
]);
$payment = $nylon->collectPayment([
'amount' => 10000,
'currency' => 'UGX',
'customer' => [
'name' => 'Jane',
'phoneNumber' => '+256700000000',
],
'description' => 'Order #1234',
]);
$payment->on('success', function (array $data): void {
echo 'Paid: ' . ($data['transaction']['reference'] ?? '') . PHP_EOL;
});
$payment->on('failed', function (array $data): void {
echo 'Failed: ' . ($data['error'] ?? '') . PHP_EOL;
});
$tx = $payment->wait();| Field | Required | Default | Description |
|---|---|---|---|
apiKey |
Yes | Must start with npk_ |
|
apiSecret |
Yes | Must start with nps_ |
|
baseUrl |
No | https://api.nylonpay.com/api/services |
Override endpoint. Config::LEGACY_BASE_URL is the original address, still served |
timeoutMs |
No | 90000 |
Request timeout in milliseconds |
maxRetries |
No | 3 |
Retry count for failed requests |
maxPollIntervalMs |
No | 2000 |
Interval between status checks |
maxPollDurationMs |
No | (none) | Optional cap on total wait time |
maxPollAttempts |
No | (none) | Optional cap on status checks |
onDelayed |
No | "wait" |
"return" or "wait" when delayed |
force |
No | false |
Bypass instance cache |
hooks |
No | null |
Lifecycle hooks |
httpClient |
No | null |
Injectable HTTP client for tests |
onError |
No | null |
Global handler for structured operation errors on this SDK instance |
The factory caches instances by apiKey + baseUrl + sha256(apiSecret). Rotating the secret yields a fresh instance.
All operations take a single associative array. Method names match the cross-language SDK spec.
collectPayment: returnsPaymentInstancecollectPaymentAndResolve: blocks until terminal, returnsResultmakePayout: returnsPaymentInstance(destinationrequiresaccountHolderName,accountNumber, andphone)makePayoutAndResolve: blocks until terminal, returnsResult(destinationrequiresphone)getStatus: one-shot status checkgetTransaction: full transaction lookuplistTransactions: paginated list with optional filtersgetTransactionsByTag: shorthand tag filterverifyPhone: pre-validate a phone number. International numbers keep their calling code (+254…stays Kenya). A local0…number is treated as Uganda.createInvoice: hosted invoice link (requires an approved Level 2 account)verifyWebhookSignature: verify an incoming webhook before you trust it
use function NileSquad\NylonPay\parseError;
$result = $nylon->getStatus(['reference' => $payment->reference]);
if ($result->isOk()) {
$status = $result->value();
} else {
$error = parseError($result->error());
// $error->reason, $error->message, $error->retryable
}With a sandbox key, collectPayment, collectPaymentAndResolve, makePayout and makePayoutAndResolve accept two test-only options:
'testOutcome' => 'success'or'fail'(or a failure code) forces the result.'prompt' => 'pin'holds the payment until the merchant types the customer's 5-digit PIN, shown on the dashboard phone simulator. The wait is up to about 2 minutes with 3 tries. The PIN is one per merchant and works with every sandbox key of that merchant.
If both are set, testOutcome wins. With neither, the sandbox decides on its own. A live key rejects both. The AndResolve variants can wait about 2 minutes with prompt, so raise maxPollDurationMs above that if you cap polling.
Events: processing, success, failed, cancelled, error.
$payment->on('success', fn (array $data) => /* ... */);
$payment->once('failed', fn (array $data) => /* ... */);
$payment->off('success', $handler);
$tx = $payment->wait();Polling runs inside wait(). If initiation fails at the server, the instance emits "error" when wait() is called.
use function NileSquad\NylonPay\verifyWebhookSignature;
$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_NYLON_SIGNATURE'] ?? '';
$valid = verifyWebhookSignature([
'payload' => $rawBody,
'signature' => $signature,
'secret' => getenv('NYLONPAY_WEBHOOK_SECRET'),
]);
if (!$valid) {
http_response_code(401);
exit;
}Verification never throws. It returns false on any failure.
- Misconfiguration and client validation throw
SdkExceptionwithreason. - Sync operations return
Resulterrors as JSON-serialized strings, useparseError(). - Branch on
reason, never message text.
Categories: auth, validation, limit, rate_limit, account, provider, duplicate, not_found, internal, network, timeout.
Requires PHP 8.2+ with curl, json, mbstring, openssl, and Composer.
composer install
composer test # unit + security
composer test:integration # I1–I19 against sandbox (.env)
composer check # cs-check + phpstan + testsIntegration tests load credentials from a .env file in the package root:
NYLONPAY_API_KEY=npk_test_...
NYLONPAY_API_SECRET=nps_test_...
NYLONPAY_BASE_URL=http://localhost:8000/api/servicesPublish gate: run composer check and the full integration suite against sandbox before any Packagist release.
- PHP SDK (this package)
- TypeScript SDK
- Python SDK
- SDK Spec
MIT