PHP SDK

Official PHP SDK for the Vatly API.

Official PHP SDK for the Vatly API. Handle subscriptions, one-off payments, tax compliance, and billing for your SaaS.

Looking for the exact field list? These guides cover the common paths. The authoritative, machine-readable schema for every endpoint lives in the OpenAPI spec — point your AI assistant or codegen tooling at it when an example leaves a field ambiguous.

Installation

The SDK is in alpha, and every alpha release may include breaking changes. Allow alpha releases, then install the SDK via Composer. prefer-stable keeps your other dependencies on stable releases.

composer config minimum-stability alpha
composer config prefer-stable true
composer require vatly/vatly-api-php

Quick start

Initialize the client with your API key and create a checkout.

API Keys

Get your API keys from the Vatly Dashboard under Settings > API.

NameTypeDescription
live_prefixProduction transactions, real charges.
test_prefixSandbox testing, no real charges.
use Vatly\API\VatlyApiClient;

$vatly = new VatlyApiClient();
$vatly->setApiKey('live_your_api_key_here');

// Create a checkout
$checkout = $vatly->checkouts->create([
    'products' => [
        ['id' => 'subscription_plan_abc123', 'quantity' => 1]
    ],
    'redirectUrlSuccess' => 'https://yourapp.com/success',
    'redirectUrlCanceled' => 'https://yourapp.com/canceled',
]);

// Redirect customer to checkout
header('Location: ' . $checkout->links->checkoutUrl->href);

Idempotency

The SDK automatically adds an Idempotency-Key header to every POST and PATCH request. This is enabled by default, so checkout creation and subscription updates are already protected without extra configuration.

GET and DELETE requests do not include an idempotency header.

Override the next mutating request

Use setIdempotencyKey() when you want to supply the key yourself. The value is used for the next POST or PATCH request and then cleared automatically.

$vatly->setIdempotencyKey('checkout-create-123');

$checkout = $vatly->checkouts->create([
    'products' => [
        ['id' => 'subscription_plan_abc123', 'quantity' => 1],
    ],
    'redirectUrlSuccess' => 'https://yourapp.com/success',
    'redirectUrlCanceled' => 'https://yourapp.com/canceled',
]);

This also works with resource methods that do not expose request options directly:

$vatly->setIdempotencyKey('subscription-update-123');

$subscription->update([
    'quantity' => 2,
]);

Per-request options on supported endpoint methods

Methods that accept a second or third options array can override the header with idempotencyKey.

$checkout = $vatly->checkouts->create([...], [
    'idempotencyKey' => 'checkout-create-123',
]);

$subscription = $vatly->subscriptions->update('subscription_123', [
    'quantity' => 2,
], [
    'idempotencyKey' => 'subscription-update-123',
]);

Custom generator or disable auto-generation

If you need a specific key format, provide your own generator implementation.

use Vatly\API\HttpClient\Idempotency\IdempotencyKeyGeneratorContract;

final class MyIdempotencyKeyGenerator implements IdempotencyKeyGeneratorContract
{
    public function generate(): string
    {
        return bin2hex(random_bytes(16));
    }
}

$vatly->setIdempotencyKeyGenerator(new MyIdempotencyKeyGenerator());

To stop the SDK from generating keys automatically:

$vatly->clearIdempotencyKeyGenerator();

Resources

The SDK provides access to all Vatly API resources.

ResourceDescription
CheckoutsCreate hosted payment pages
CustomersManage customer records
SubscriptionsRecurring billing
Subscription PlansDefine subscription products
One-Off ProductsSingle purchase products
OrdersTransaction records
RefundsProcess refunds
ChargebacksHandle disputes
WebhooksReal-time event notifications
Webhook EndpointsRegister delivery endpoints

Identifying your integration

Every request's User-Agent starts with vatly/vatly-api-php/<version>, followed by the PHP and HTTP client versions. A package or plugin built on this client adds its own token with addVersionString(), using its Composer package name (or plugin slug) and version, so Vatly sees every package involved:

$vatly->addVersionString('acme/vatly-shop-plugin/1.4.0');
// User-Agent: vatly/vatly-api-php/0.1.0-alpha.45 PHP/8.4.1 curl/8.5.0 acme/vatly-shop-plugin/1.4.0

Error handling

Every exception the SDK throws implements Vatly\API\Exceptions\VatlyException, so one catch covers API errors and webhook signature failures.

When the API answers with an error, the SDK throws an ApiException, or the subclass for the HTTP status:

StatusExceptionWhen
401AuthenticationExceptionThe API key is missing or invalid.
403ForbiddenExceptionThe API key is invalid, revoked, or not allowed to perform this operation.
404NotFoundExceptionThe resource does not exist, or not in the API key's mode.
409ConflictExceptionFor example, an idempotency key reused with other parameters, or a request still in progress.
422ValidationExceptionThe request is invalid. getErrors() lists the messages per field.
429RateLimitExceptionToo many requests. Wait getRetryAfter() seconds.
503ServiceUnavailableExceptionVatly is temporarily unavailable, or creating checkouts is paused. Nothing was processed: retry the same request, with the same idempotency key, after getRetryAfter() seconds.
otherApiExceptionAny other error status.

An ApiException without a status code means no response arrived (for example, a connection error), or the SDK refused the call before sending it.

MethodReturns
getMessage()The API's error message. It never contains the request body or the API key.
getStatusCode()The HTTP status, or null when there was no response.
getErrors()Validation messages per field (dot notation), such as ['products.0.id' => ['The selected products.0.id is invalid.']].
getDetails()The error's details object, such as ['idempotency_outcome' => 'in_progress'].
getRetryAfter()Seconds from the Retry-After header, sent on 429 and 503, and on a 409 while an idempotent request is in progress.
getErrorCode()The error's machine-readable code, such as service_unavailable, or null. New codes may be added.
getResponseBody()The raw response body.

Branch on the exception class or status code, not on the message text.

use Vatly\API\Exceptions\ApiException;
use Vatly\API\Exceptions\RateLimitException;
use Vatly\API\Exceptions\ValidationException;

try {
    $checkout = $vatly->checkouts->create([...]);
} catch (ValidationException $e) {
    foreach ($e->getErrors() as $field => $messages) {
        // e.g. 'products.0.id' => ['The selected products.0.id is invalid.']
    }
} catch (RateLimitException $e) {
    $waitSeconds = $e->getRetryAfter() ?? 60;
} catch (ApiException $e) {
    $status = $e->getStatusCode(); // null when no response arrived
}

Money

Every amount is a Vatly\API\Types\Money with a currency and a value. value is the exact decimal string the API sent, never rounded, with as many decimals as the API sends ("17.35" EUR, "100" JPY).

MethodReturns
toMinorUnits()The amount in the currency's minor units, using its own number of decimals: "17.35" EUR is 1735, "100" JPY is 100.
toCents()The amount in cents, for two-decimal currencies such as EUR and USD.

Both use integer math. Instead of dropping part of the amount, they throw a MoneyConversionException: when the value has more decimals than the currency ("17.355" EUR), or for toCents(), when the currency does not have two decimals. Store toMinorUnits() together with the currency if you may receive currencies other than EUR and USD.


Backward compatibility

From v1.0.0, this package follows semantic versioning: a minor or patch release does not break code that uses its public API. These are not part of that API:

  • Anything marked @internal, such as ResourceFactory, the webhook event constructors (build events with WebhookEventFactory), and FakeIdempotencyKeyGenerator.
  • Extending the SDK's classes. Subclassing them is not covered by semver; only these interfaces are meant to be implemented: HttpClientInterface, DebuggableHttpClientInterface, HttpClientFactoryInterface and IdempotencyKeyGeneratorContract. The SDK may add methods to its other interfaces, such as WebhookEventInterface, in a minor release.

Resources only set the properties they declare. A field the API adds before the SDK types it is not set on the resource; read it from getRawPayload(), which returns the JSON exactly as the API sent it. When a later 1.x release types that field, it adds a property, and getRawPayload() stays the same.

A webhook event the SDK doesn't type yet arrives as UnsupportedWebhookReceived, and a later 1.x release may give it its own class. To handle such an event, match on WebhookEventInterface and getEventName(), not on UnsupportedWebhookReceived; see Webhooks.

Requirements

  • PHP 8.1+
  • cURL extension
  • JSON extension
Copyright © 2026