cryptpays / sdk-php
Official PHP SDK for the CryptPays Merchant API
Requires
- php: ^8.2
- ext-json: *
- ext-openssl: *
- guzzlehttp/guzzle: ^7.9
- psr/http-client: ^1.0
- psr/http-factory: ^1.1
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Official PHP client for the public CryptPays Merchant API. Version 0.1.0 is an initial, pre-stable release.
The SDK covers live currency discovery, currency information, payment-address creation, public pricing, callback public-key retrieval, server-side payment logs, and RSA-SHA256 callback verification. It does not contain wallet keys, blockchain signing, payout logic, Admin APIs, or private infrastructure endpoints.
- Website: cryptpays.com
- Developer documentation: docs.cryptpays.com
- Source and issues: github.com/cryptpays/cryptpays-php
Requirements
- PHP 8.2 or newer
- JSON and OpenSSL extensions
- A PSR-18 HTTP client and PSR-17 request/stream factories
Guzzle is included as the default HTTP implementation. Any compatible PSR-18 client can be injected.
Installation
Once the package is approved and published:
composer require cryptpays/sdk-php:^0.1
For this local repository:
composer config repositories.cryptpays path /path/to/cryptpays-sdk/php composer require cryptpays/sdk-php:@dev
Use a Composer path repository while the package remains unpublished.
Quick start
This is the complete basic flow: initialize the default client, select a live currency, create a JSON-callback payment, and display its deposit address.
<?php use CryptPays\CryptPaysClient; use CryptPays\Enum\CallbackTransport; use CryptPays\Request\CreatePaymentRequest; $client = CryptPaysClient::create(); $currency = $client->listCurrencies()->get('bep20_usdt'); if ($currency === null) { throw new RuntimeException('The selected currency is not currently available.'); } $payment = $client->createPayment(new CreatePaymentRequest( ticker: $currency->ticker, callbackUrl: 'https://merchant.example/cryptpays/callback?order_id=opaque-random-reference', addressOut: '0x1111111111111111111111111111111111111111', callbackTransport: CallbackTransport::JsonPost, )); echo $payment->addressIn;
The values are synthetic. A runnable local copy is available at examples/quick-start.php.
Create a client
<?php use CryptPays\Config\ClientConfig; use CryptPays\CryptPaysClient; $client = CryptPaysClient::create(new ClientConfig( connectTimeoutSeconds: 5.0, requestTimeoutSeconds: 15.0, ));
The Merchant API is keyless. Do not invent or send an API key. HTTPS is required by default; insecure HTTP must be enabled explicitly and is intended only for isolated local testing.
When injecting another PSR-18 client, configure connection and total timeouts on that client. PSR-18 does not define portable per-request timeout options, so the values in ClientConfig are applied by the built-in Guzzle factory only.
Advanced integrations can inject any PSR-18 client with PSR-17 request and stream factories directly:
$client = new CryptPaysClient( httpClient: $psr18Client, requestFactory: $psr17RequestFactory, streamFactory: $psr17StreamFactory, config: $config, );
Basic integrations do not need to construct or understand these transport objects.
Discover currencies and pricing
$currencies = $client->listCurrencies(); $usdt = $currencies->get('bep20_usdt'); $info = $client->getCurrencyInfo('bep20_usdt'); $minimum = $info->minimumTransaction === null ? 'currently unavailable' : (string) $info->minimumTransaction; $pricing = $client->getPricing(); foreach ($pricing->tiers as $tier) { echo (string) $tier->feePercent; }
Currency availability is runtime data. Use listCurrencies() rather than a hardcoded network or token list. Monetary and percentage values are represented by DecimalString; they are never converted to floats.
Minimum deposits are runtime metadata and can be null when no safe value is available. They are not an expected order amount, and separate deposits are not aggregated merely to reach a minimum.
Create or reuse a payment address
use CryptPays\Enum\CallbackTransport; use CryptPays\Enum\PaymentPriority; use CryptPays\Request\CreatePaymentRequest; $callbackUrl = 'https://merchant.example/cryptpays/callback?order_id=opaque-random-reference'; $addressOut = '0x1111111111111111111111111111111111111111'; $payment = $client->createPayment(new CreatePaymentRequest( ticker: 'bep20_usdt', callbackUrl: $callbackUrl, addressOut: $addressOut, notifyPending: false, callbackTransport: CallbackTransport::JsonPost, priority: PaymentPriority::Default, )); echo $payment->addressIn; echo (string) $payment->minimumTransactionCoin;
The SDK sends creation as JSON POST and defaults callback delivery to JSON POST. It verifies that the returned address_out and callback_url exactly match the request.
Payment creation has no automatic retry. If the outcome is uncertain after a transport failure, reconcile deliberately using the same exact request identity. A compatible repeated create returns the stored immutable configuration; it does not update payout address, confirmations, priority, callback transport, pending behavior, conversion, or the stored minimum snapshot.
CryptPays creation does not register an expected order amount, expiration, refund, cancellation, underpayment, or overpayment policy. Those behaviors must not be inferred from this SDK.
Explicit safe-read retries
Retries are disabled by default. They can be enabled for read-only SDK methods:
use CryptPays\Config\RetryPolicy; $config = new ClientConfig( retryPolicy: RetryPolicy::safeReads( maxAttempts: 3, initialDelayMilliseconds: 100, maximumDelayMilliseconds: 1000, ), ); $client = CryptPaysClient::create($config);
The bounded policy retries PSR transport failures and HTTP 429, 502, 503, and 504 by default. It never applies to createPayment().
Both integer-second and standard HTTP-date Retry-After values are honored within the configured maximum delay.
Pricing schedule lookup
PricingSchedule::tierForVolume() selects the public schedule tier for a caller-supplied rolling volume using exact decimal comparison:
$tier = $client->getPricing()->tierForVolume('12500.00');
The lower bound is inclusive and the upper bound is exclusive. This helper does not determine the merchant's authoritative rolling volume, guarantee the actual callback percentage, estimate network costs, or predict settlement. The confirmed callback remains authoritative for the payment's actual fee and fee_coin.
Callback verification
Verify the signature and timestamp against the exact raw request before decoding the payload:
use CryptPays\Request\CallbackRequest; use CryptPays\Webhook\CallbackVerifier; // Fetch outside the callback hot path and cache using an application-managed TTL. $publicKey = $client->getCallbackPublicKey(); $verifier = new CallbackVerifier($publicKey); $callback = new CallbackRequest( method: $_SERVER['REQUEST_METHOD'], // Use the externally configured callback host, not an untrusted Host header. host: 'merchant.example', requestTarget: $_SERVER['REQUEST_URI'], // Exact path and query. rawBody: file_get_contents('php://input'), timestamp: $_SERVER['HTTP_X_CRYPTPAY_TIMESTAMP'] ?? '', signature: $_SERVER['HTTP_X_CRYPTPAY_SIGNATURE'] ?? '', ); $verified = $verifier->verify($callback); $payload = $verified->jsonPayload(); // Recommended JSON POST transport. if ($payload->isConfirmed()) { // In one durable transaction: validate the order, callback identity and coin, // allow pending -> sent, and fulfill this UUID exactly once. } // Return exactly HTTP 200 only after successful processing.
See Callback verification for the canonical request and lifecycle rules. The freshness window may be reduced for stricter deployments, but cannot be increased beyond the backend protocol's 300-second limit.
The same verified callback object supports every gateway transport:
use CryptPays\Enum\CallbackTransport; $json = $verified->jsonPayload(); $form = $verified->formPayload(); $get = $verified->getPayload(); // Or select explicitly from the immutable creation configuration: $payload = $verified->payload(CallbackTransport::JsonPost);
Parsing is transport-aware and happens only from the authenticated raw request target and body. It rejects duplicate parameters, malformed percent encoding, duplicate JSON object fields, and query/body conflicts. Safe application references retained from the registered callback URL are available through $payload->additional; unknown additive callback fields are preserved there too. JSON POST remains recommended because it avoids form/query scalar coercion.
CallbackPayload::isPending() represents result=pending, pending=1; isConfirmed() represents result=sent, pending=0. Both stages deliberately share one UUID. The SDK validates those combinations but does not persist, credit, or fulfill anything.
Application-owned durable processing must allow pending to transition to confirmed, accept confirmed-first delivery, ignore a delayed pending event after confirmation, and make repeated or concurrent confirmed delivery fulfill exactly once. Commit that transaction before returning exact HTTP 200. If it fails, return a non-200 response so CryptPays can retry.
Payment logs
$logs = $client->getPaymentLogs('bep20_usdt', $callbackUrl);
getPaymentLogs() is for trusted server-side reconciliation only. The complete callback URL acts as a capability-sensitive lookup value and the response can contain addresses, transaction identifiers, delivery destinations, and merchant response bodies. Never expose it to browsers, mobile clients, analytics, or ordinary application logs.
More examples
See Merchant examples for discovery, payment reuse, all three callback transports, transactional lifecycle guidance, pricing, payment logs, public-key refresh, and exception handling. The framework-neutral callback reference is examples/callback-handler.php.
QR generation is intentionally not a core dependency. See QR code options and optional address-only recipe; no QR library is installed by this package.
Exceptions
ApiException: structured Merchant API error with HTTP status, numeric API code and identifier.RateLimitException: unstructured HTTP 429 response.HttpException: other unexpected HTTP status.TransportException: the PSR-18 client did not return a response.MalformedResponseException: response JSON or a typed contract field was invalid.CallbackVerificationException: timestamp, key, canonical request, base64, or signature verification failed.CallbackPayloadException: a verified GET, form, or JSON callback did not match the public callback payload contract.ConfigurationExceptionandInvalidArgumentException: unsafe or invalid local configuration/input.
Do not include callback URLs in exception telemetry. SDK exception messages intentionally omit request URIs and bodies.
Development
composer validate --strict
composer test
composer analyse
composer format:check
composer test:coverage
composer test:coverage:check
Tests use mocked PSR-18 transport and deterministic callback vectors. They never make a real payment or call a live CryptPays endpoint.
The language-neutral synthetic fixture at tests/Fixtures/conformance-v1.json captures API responses, decimals, lifecycle pairs, signed transport vectors, strict signature failures, timestamp boundaries, and Retry-After forms for later cross-SDK reuse.
PHPStan runs at level 8. PHP CS Fixer enforces PSR-12-compatible rules. Coverage requires PCOV, Xdebug, or another PHPUnit-compatible coverage driver; the project does not install a system-wide driver.
See CONTRIBUTING.md before proposing a change. Report security issues privately as described in SECURITY.md, never through a public issue.
License
MIT. The included license and package publication remain subject to CryptPays project-owner approval.