leto / domain-api
PHP client for the LETO Domain API (domain registration, DNS, transfers and more for LETO partners).
Requires
- php: ^8.1
- ext-json: *
- guzzlehttp/guzzle: ^7.5
- guzzlehttp/psr7: ^2.4
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP client for the LETO Domain API: register, renew and transfer domains, manage DNS, contacts, forwarding and more from your own platform, billed to your LETO partner balance.
- Every API operation as a typed method (
$client->domains()->register(...)), generated from the API's OpenAPI document. See OPERATIONS.md for the full list. - Errors as exceptions with the API's stable error
code. - Safe retries, automatic
Idempotency-Keyon requests that charge your balance. - Page iteration over every list endpoint.
- Request and response shapes for PHPStan, Psalm and PhpStorm.
Requirements
- PHP 8.1 or later with
ext-json - Guzzle 7 (installed with the package). Any PSR-18 HTTP client can be used instead.
Installation
composer require leto/domain-api
Quick start
Create an API key in the partner console (it starts with leto_sk_). Keep it on the server.
use Leto\DomainApi\LetoClient; $client = new LetoClient(getenv('LETO_API_KEY')); $status = $client->account()->getStatus(); echo $status['balance']['amount'], ' ', $status['balance']['currency'], "\n";
Responses are the decoded JSON bodies, as documented in the API reference. Most have the
standard envelope { code, message, data, timestamp, success }; the result is in data.
TLD prices
// One TLD $com = $client->pricing()->getTld('com')['data'][0]; echo $com['prices']['registration'], ' ', $com['currency'], "\n"; // Every TLD, loading the pages as you go foreach ($client->pricing()->listTlds(['size' => 100])->autoPaginate() as $tld) { printf("%-12s %s %s\n", $tld['tld'], $tld['prices']['registration'], $tld['currency']); }
Quote, then register at that price
Prices can change (a promotion ends, a price list is updated). Get a quote, show it, and send
its total as expectedPrice. If the price changed in the meantime, the API refuses the order
with PRICE_CHANGED and charges nothing.
use Leto\DomainApi\RequestOptions; if ($client->domains()->check('example.com')['data']['available']) { $quote = $client->pricing()->quote('example.com', ['period' => 1])['data']; // Show $quote['total'] and $quote['currency'] to your customer, then: $result = $client->domains()->register([ 'domain' => 'example.com', 'period' => 1, 'contact' => ['registrant' => $contactId, 'administrative' => $contactId], 'nameservers' => ['ns1.example.net', 'ns2.example.net'], 'expectedPrice' => $quote['total'], ], new RequestOptions(idempotencyKey: $order->idempotencyKey)); echo 'Expires ', $result['data']['expiresAt'], "\n"; }
The same in one call, with an optional check before anything is charged:
$result = $client->domains()->registerWithQuote( $body, // the register() body without expectedPrice fn (array $quote): bool => $quote['total'] <= $maxPrice, );
renewWithQuote($domainName, $body) and transfers()->initiateWithQuote($body) work the same
way. When the callback returns false, QuoteDeclinedException is thrown and nothing is charged.
Contacts are created first with $client->contacts()->create([...]); use the id from the
response as registrant and administrative.
Errors
Every API error is a LetoApiException. Branch on $e->errorCode (stable, only ever added
to), not on the message. Common cases have their own subclasses.
use Leto\DomainApi\Exception\ApiConnectionException; use Leto\DomainApi\Exception\InsufficientBalanceException; use Leto\DomainApi\Exception\LetoApiException; use Leto\DomainApi\Exception\NotFoundException; use Leto\DomainApi\Exception\PriceChangedException; try { $client->domains()->renew('example.com', ['period' => 1, 'expectedPrice' => 10.99]); } catch (PriceChangedException $e) { // Nothing was charged. Ask again with the new price. echo "Now {$e->actual} {$e->currency} instead of {$e->expected}\n"; } catch (InsufficientBalanceException $e) { echo "Top up your balance\n"; } catch (NotFoundException $e) { echo "No such domain in your account\n"; } catch (LetoApiException $e) { // $e->httpStatus, $e->errorCode, $e->getMessage(), $e->data, $e->extra error_log("{$e->errorCode}: {$e->getMessage()} (request {$e->requestId})"); } catch (ApiConnectionException $e) { // The API could not be reached. For a charging request the outcome is unknown: // send it again later with the same key ($e->idempotencyKey). }
When a registry call fails or times out
A charging request (registration, renewal, restore, transfer) can fail with a ServerException
whose errorCode is API_TIMEOUT (504), NETWORK_ERROR or REGISTRY_CONNECTION_FAILED (502).
Your balance was not charged, but the registry may still have carried out the request. The SDK
does not resend these requests by itself; sending one again is your call, and it is safe:
- Registration, restore and transfer: the registry refuses a second request for the same domain, so a request that already went through fails instead of being applied twice.
- Renewal: the next renewal of the same domain (within 7 days) first reads the registry expiry
date. If the earlier renewal was applied, the API does not renew again; it records the earlier
renewal, charges it once and returns the registry expiry date. Send the same
period, otherwise the API answers 409OPERATION_NOT_ALLOWED. If the registry cannot be read, you get 502 and nothing is charged; try again later.
Use the same Idempotency-Key when you send it again.
| Exception | When |
|---|---|
BadRequestException |
400, 422 (ValidationException for VALIDATION_FAILED with $fields, IdempotencyKeyReusedException) |
AuthenticationException |
401: missing, wrong or revoked API key |
InsufficientBalanceException |
BALANCE_INSUFFICIENT, BALANCE_NEGATIVE, TRANSFER_INSUFFICIENT_BALANCE |
PermissionDeniedException |
403 (IpNotAllowedException for IP_NOT_ALLOWED) |
NotFoundException |
404 |
ConflictException |
409 (PriceChangedException, IdempotencyInProgressException) |
RateLimitException |
429, with $retryAfter |
ServerException |
5xx except 501 |
ApiConnectionException |
no response (DNS, TLS, connection, timeout) |
UnexpectedResponseException |
a 2xx response without a JSON body |
All of them implement Leto\DomainApi\Exception\LetoException. $e->requestId is the
X-Request-Id of the response; quote it when you contact LETO about a failed call.
Pages
List methods return a Page. Iterate it for the items of that page, or call autoPaginate()
for every item of every page (the next page is loaded only when you get there).
$page = $client->domains()->list(['status' => ['active', 'expired'], 'size' => 100]); echo $page->total(), " domains\n"; foreach ($page->autoPaginate() as $domain) { echo $domain['domainName'], ' ', $domain['expiresAt']['date'], "\n"; } // GET /transactions keeps its items in data.transactions; the Page handles that. foreach ($client->transactions()->list(['type' => 'charge', 'limit' => 100])->autoPaginate() as $tx) { echo $tx['createdAt'], ' ', $tx['amount'], ' ', $tx['currency'], "\n"; }
$page->items(), $page->body(), $page->pagination(), $page->hasNextPage() and
$page->nextPage() are there when you need them.
Idempotency
Registration, renewal, restore and transfer charge your balance. The SDK sends an
Idempotency-Key with each of these calls (a new UUID unless you pass one), so it can retry them
after a lost connection without charging twice. A request with the same key within 24 hours
returns the first successful result.
When a retry might happen in another process (a queue worker, a crash, the next cron run), create the key yourself and store it with your order before calling:
use Leto\DomainApi\IdempotencyKey; $order->idempotencyKey ??= IdempotencyKey::generate(); // save the order here $client->domains()->renew('example.com', ['period' => 1], new RequestOptions(idempotencyKey: $order->idempotencyKey)); $client->lastResponse()->replayed; // true when the API returned the stored first result
Other endpoints do not accept a key; passing one throws InvalidArgumentException.
Retries and timeouts
Up to 2 retries by default. The SDK waits as long as Retry-After says (up to maxRetryAfter
seconds) or backs off exponentially (about 0.5 s, 1 s, 2 s).
- GET requests: connection errors, 429, 502, 503 and 504.
- Requests with an Idempotency-Key: connection errors, 429, 503, 409
IDEMPOTENCY_REQUEST_IN_PROGRESS, and 502 or 504 pages from a proxy in front of the API. A 502 or 504 error from the API itself is not retried (see "When a registry call fails or times out"). - Other requests are never retried automatically.
$client = new LetoClient($apiKey, [ 'timeout' => 30, // seconds per request, default 60 'connectTimeout' => 5, // default 10 'maxRetries' => 3, // default 2, 0 turns retries off 'maxRetryAfter' => 30, // longest Retry-After to wait for, default 60 'userAgentSuffix' => 'my-panel/2.1', ]); // Per call $client->domains()->get('example.com', new RequestOptions(maxRetries: 0));
Your own HTTP client
Pass any PSR-18 client (and PSR-17 factories if you do not want guzzlehttp/psr7). Timeouts are then configured on that client.
$client = new LetoClient($apiKey, [ 'httpClient' => new Symfony\Component\HttpClient\Psr18Client(), ]);
Static analysis
Every method declares the array shape it takes and returns (as PHPStan/Psalm type aliases in
Leto\DomainApi\Schemas), so PHPStan, Psalm and PhpStorm know the keys:
$status = $client->account()->getStatus(); $status['balance']['amout']; // PHPStan: Offset 'amout' does not exist on array{amount: float|int, ...}
Enum values in responses are typed as plain strings because the API may add values.
Request details
$info = $client->lastResponse(); $info->statusCode; // 200 $info->requestId; // X-Request-Id $info->idempotencyKey; // key sent with the last request, if any $info->attempts; // 1, or more after retries
Versioning
The SDK follows semantic versioning. The API itself only changes in
backward compatible ways; new endpoints and fields arrive in minor SDK releases.
Leto\DomainApi\Version::API is the API document version the release was built from.
License
MIT. See LICENSE.
한국어 안내
LETO 도메인 도매 API 의 PHP SDK 입니다. PHP 8.1 이상에서 동작하고, 기본 HTTP 클라이언트로 Guzzle 7 을 씁니다.
composer require leto/domain-api
$client = new Leto\DomainApi\LetoClient(getenv('LETO_API_KEY')); $status = $client->account()->getStatus(); // 잔액·통화 $page = $client->domains()->list(['size' => 100]); // 목록은 Page, autoPaginate() 로 전체 순회
- API 키는 파트너 콘솔에서 발급하며
Authorization: Bearer로 보냅니다. 서버에만 두세요. - 오류는
LetoApiException으로 던집니다. 분기는 메시지가 아니라$e->errorCode로 합니다. 문의할 때는$e->requestId(X-Request-Id)를 함께 알려 주세요. - 등록·갱신·복원·이전 요청에는
Idempotency-Key를 자동으로 붙이고, 연결 오류·429·503 에서 같은 키로 다시 보냅니다. 다른 프로세스에서 다시 시도할 수 있다면 키를 직접 만들어 주문과 함께 저장해 두세요(IdempotencyKey::generate()). - 이 요청이
API_TIMEOUT(504)이나NETWORK_ERROR·REGISTRY_CONNECTION_FAILED(502)로 실패하면 잔액은 차감되지 않았지만 레지스트리에서는 처리됐을 수 있습니다. SDK 는 저절로 다시 보내지 않지만, 같은 키로 다시 보내도 안전합니다. 등록·복원·이전은 레지스트리가 두 번째 요청을 거절하고, 갱신은 API 가 레지스트리 만료일을 먼저 확인해 이미 갱신됐으면 다시 갱신하지 않고 한 번만 기록·과금합니다 (같은period로 보내야 하며, 다르면 409). - 가격이 바뀌는 사이에 결제되지 않게 하려면 견적의
total을expectedPrice로 보내거나registerWithQuote()를 쓰세요. 가격이 달라졌으면PriceChangedException이 나고 차감되지 않습니다. - 전체 메서드 목록은 OPERATIONS.md, API 문서는 https://partners.leto.kr/docs 에 있습니다.