PHP
Render documents, wait for async renders, verify webhooks and create embedded editor sessions with the official PHP SDK.
druckling/druckling-php is the official PHP client for the Druckling API. It has typed, readonly models and one exception class per kind of error. It needs nothing beyond ext-curl and ext-json, and can send its requests through any PSR-18 client instead.
Install
Requirements:
- PHP 8.1 or later with
ext-curlandext-json. - Optional: a PSR-18 HTTP client and PSR-17 factories, to use
Psr18Transport.
The package isn't on Packagist yet. Install it from the Druckling source repository as a Composer path repository:
git clone https://github.com/vulpery/druckling.git
# then, in your project
composer config repositories.druckling path /path/to/druckling/src/integrations/sdk-php
composer require druckling/druckling-php:@devComposer symlinks path repositories by default. If your build can't follow the link (a Docker image, for example), set "options": { "symlink": false } on the druckling repository in composer.json to copy the files instead.
Then create a key under Developers › API keys and expose it as DRUCKLING_API_KEY.
Configuration
use Druckling\Druckling;
$druckling = new Druckling(
apiKey: 'dr_test_...',
baseUrl: 'https://druckling-nine.vercel.app',
timeout: 60.0,
maxRetries: 2,
defaultHeaders: ['X-Correlation-Id' => 'checkout-42'],
);| Argument | Default | Notes |
|---|---|---|
apiKey | DRUCKLING_API_KEY | An dr_test_… or dr_live_… key, sent as Authorization: Bearer …. Read with getenv(), then $_ENV and $_SERVER. |
baseUrl | DRUCKLING_BASE_URL, then https://druckling-nine.vercel.app | With or without a trailing /v1. Must be an http or https URL. |
timeout | 60.0 | Seconds per HTTP attempt with the built-in transport, see Retries and timeouts. |
maxRetries | 2 | Retries after the first attempt. 0 turns retries off. |
transport | new CurlTransport() | Any Druckling\Http\Transport, such as Psr18Transport. |
defaultHeaders | [] | Extra headers on every API request. |
Use named arguments. The constructor throws a DrucklingException without an API key, for an invalid base URL, a timeout of 0 or less, or a negative maxRetries.
$druckling->withOptions(timeout: 120.0, maxRetries: 4)returns a copy with other settings that shares the transport.$druckling->isTestMode()istruefordr_test_…keys.$druckling->baseUrl()is the origin requests go to, without/v1.
Laravel
Once you cache the configuration (php artisan config:cache), Laravel no longer loads .env, so the SDK can't read DRUCKLING_API_KEY from that file. Add the key to config/services.php and pass it in a service provider instead: $this->app->singleton(Druckling::class, fn () => new Druckling(apiKey: config('services.druckling.key')));
Built-in curl transport
CurlTransport reuses one curl handle, so connections stay open between requests. Its connect timeout is 10 seconds; change it with new CurlTransport(connectTimeout: 5.0) and pass that as transport.
PSR-18 clients
To send requests through Guzzle, Symfony HttpClient or any other PSR-18 client (for proxies, middleware or tracing), wrap it in Psr18Transport with PSR-17 request and stream factories:
composer require guzzlehttp/guzzleuse GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Druckling\Http\Psr18Transport;
use Druckling\Druckling;
$factory = new HttpFactory();
$druckling = new Druckling(transport: new Psr18Transport(new Client(['timeout' => 60]), $factory, $factory));With a PSR-18 client, timeouts are whatever that client is configured with; the SDK's timeout doesn't apply. Network errors and timeouts from the client both surface as ConnectionException.
Render a document
documents->create() validates data against the template's JSON Schema and renders the document. By default it waits for the file and returns a rendered document:
<?php
require __DIR__ . '/vendor/autoload.php';
use Druckling\Druckling;
$druckling = new Druckling(); // reads DRUCKLING_API_KEY
$invoice = [
'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'],
'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'],
'line_items' => [
['description' => 'Brand identity, phase 2', 'qty' => 1, 'rate' => 4800, 'amount' => 4800],
['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160],
],
'totals' => ['subtotal' => 6960, 'tax' => 556.8, 'amount' => 7516.8],
'payment' => ['url' => 'https://pay.example.com/INV-2041'],
];
$document = $druckling->documents->create(
template: 'invoice-standard',
data: $invoice,
filename: 'INV-2041.pdf',
);
echo $document->id, ' ', $document->status, ' ', $document->pages, PHP_EOL; // pdf_… rendered 1
$druckling->documents->downloadTo($document, __DIR__ . '/INV-2041.pdf');The arguments are template (slug), data, and optionally version (a published version number, default 'latest'), filename, async, language and format.
data is sent as JSON. An empty top-level array becomes {}; for an empty object deeper in the payload, pass new \stdClass(). It must match the template's schema; $druckling->templates->get('invoice-standard')->sampleData is a payload that renders. See Variables.
The returned Druckling\Model\Document has the API's fields as camelCase properties (sizeBytes, contentType, testMode, …), with createdAt and expiresAt as DateTimeImmutable. isRendered(), isFailed() (failed or expired) and isFinal() check the status; the Druckling\Model\DocumentStatus constants name the values. $document->raw holds the response exactly as the API returned it, including fields the model doesn't declare yet, such as image and batch. See Retrieve a document for every field.
Render asynchronously and wait
Pass async: true to queue the render. create() returns right away with status queued, and the file is rendered in the background. Use documents->wait() to poll until it's done, or receive a webhook:
use Druckling\Exception\DocumentFailedException;
use Druckling\Exception\WaitTimeoutException;
$queued = $druckling->documents->create(template: 'invoice-standard', data: $invoice, async: true);
echo $queued->status; // queued
try {
$document = $druckling->documents->wait($queued, timeout: 120.0, interval: 1.0);
$pdf = $druckling->documents->download($document);
} catch (DocumentFailedException $e) {
error_log('Render failed: ' . ($e->document->error?->message ?? $e->document->status));
} catch (WaitTimeoutException $e) {
error_log("Still {$e->document->status}; check again later");
}wait(Document|string $document, float $timeout = 120.0, float $interval = 1.0) accepts a Document or a document ID and polls documents->get() every $interval seconds. It returns the document once it's rendered. It throws DocumentFailedException when the document ends failed or expired ($e->document holds it), and WaitTimeoutException when the next poll would pass $timeout ($e->document is the last state seen).
Waiting blocks the PHP process, and each poll is an API request that counts toward your key's rate limit. In a web request, prefer webhooks or a queued job.
Download the file
The file is a PDF, a PNG or an XML e-invoice, depending on the document's format:
documents->download($document)returns it as a string.documents->downloadTo($document, $path)writes it to a file, and throws aDrucklingExceptionif it can't.
Both fetch the file from the document's signed url; your API key isn't sent there.
$bytes = $druckling->documents->download($document);
$druckling->documents->downloadTo($document, __DIR__ . '/' . $document->filename);- Pass a document ID instead of a
Documentto fetch the document first and get a fresh signed URL. Do that for documents you stored earlier: a signed URL works for at most 7 days, and never after the file is deleted atexpiresAt. - A document that is
failedorexpiredthrowsDocumentFailedException. One that is stillqueuedorrenderingthrows aDrucklingException; callwait()first. - A failed request to the signed URL throws an
ApiExceptionwitherrorCodedownload_failed.
PNG and XML output
Pass format: 'png' to render the first page as a PNG at 144 dpi instead of a PDF:
$preview = $druckling->documents->create(template: 'invoice-standard', data: $invoice, format: 'png');
echo $preview->contentType, ' ', $preview->pages; // image/png 1
$druckling->documents->downloadTo($preview, __DIR__ . '/INV-2041.png');The SDK doesn't support the API's image options yet (image.page to pick another page, image.scale from 0.5 to 4 pixels per point, 36 to 288 dpi). To use them, send the request with the SDK's transport and hand the result to its helpers:
use Druckling\Exception\ApiException;
use Druckling\Http\CurlTransport;
use Druckling\Http\Request;
use Druckling\Model\Document;
$response = (new CurlTransport())->send(new Request(
'POST',
'https://druckling-nine.vercel.app/v1/documents',
['Authorization' => 'Bearer ' . getenv('DRUCKLING_API_KEY'), 'Content-Type' => 'application/json'],
json_encode(
['template' => 'invoice-standard', 'data' => $invoice, 'format' => 'png', 'image' => ['page' => 1, 'scale' => 4]],
JSON_THROW_ON_ERROR,
),
60.0,
));
if (!$response->isSuccessful()) {
throw ApiException::fromResponse($response); // the same typed exceptions as the SDK
}
$hiRes = Document::fromArray(json_decode($response->body, true, 512, JSON_THROW_ON_ERROR));
$druckling->documents->downloadTo($hiRes, __DIR__ . '/INV-2041@4x.png');XML output is for e-invoice templates set to XRechnung or Peppol BIS: they render format: 'xml' by default, contentType is application/xml, and $document->einvoice describes the format and profile. Factur-X / ZUGFeRD templates render a PDF/A-3 only. A format the template can't produce throws a ValidationException with $e->field === 'format'. See PNG output and E-invoicing.
Languages
A template can have several languages: a default one plus translations. Pass language to render one of them. For example, after adding German to the invoice-standard template:
$template = $druckling->templates->get('invoice-standard');
$template->language; // 'en'
$template->languages; // ['en', 'de'], default first
$rechnung = $druckling->documents->create(
template: 'invoice-standard',
data: $invoice,
filename: 'RE-2041.pdf',
language: 'de',
);
echo $rechnung->language; // deWithout language the template's default is used. Texts without a translation fall back to the default language; numbers, dates, hyphenation and the PDF's language metadata follow the requested one. A regional tag such as de-AT renders de. A language the template doesn't have throws a ValidationException with $e->field === 'language'. See Languages.
List documents
documents->list() fetches one page of documents, newest first, as a CursorPage. Iterating the page walks every matching document, fetching the following pages as you go:
use Druckling\Model\DocumentStatus;
foreach ($druckling->documents->list(status: DocumentStatus::FAILED, template: 'invoice-standard') as $document) {
echo $document->id, ' ', $document->createdAt->format('c'), ' ', $document->error?->message, PHP_EOL;
}
$page = $druckling->documents->list(limit: 25);
$page->data; // up to 25 documents
$page->nextCursor; // pass as list(cursor: …) to resume later, or null
$page->hasNextPage(); // bool
$page->nextPage(); // the next CursorPage, or nullFilters: limit (1 to 100, default 25), cursor, status (queued, rendering, rendered, failed, expired) and template (slug). A test key lists test documents, a live key live ones. See List documents. Fetch one document with documents->get('pdf_…').
Templates
foreach ($druckling->templates->list() as $template) {
echo $template->slug, ' ', $template->status, ' v', $template->latestVersion ?? '-', PHP_EOL;
}
$template = $druckling->templates->get('invoice-standard');
$template->requiredFields; // ['invoice.number', 'invoice.due_date', 'customer.name', …, 'line_items[].qty', …]
$template->jsonSchema; // the JSON Schema `data` is validated against
$template->sampleData; // a payload that renders- Reading templates needs a Full access key; a Render only key gets a
PermissionDeniedException. templates->list()returns aListResponsewith every template of the workspace, drafts included. It isn't paginated: iterate it,count()it, or read->data. See List templates and Retrieve a template.jsonSchema,sampleData,requiredFieldsandlanguagescome from the latest published version, or from the draft if the template was never published.- Only published templates render (
$template->isPublished()). Pin a version withdocuments->create(..., version: 3).
Errors
Every exception the SDK throws extends Druckling\Exception\DrucklingException, itself a RuntimeException. Errors from the API are ApiException subclasses. All classes live in Druckling\Exception:
DrucklingException
├── ApiException
│ ├── ValidationException
│ ├── AuthenticationException
│ ├── PermissionDeniedException
│ ├── NotFoundException
│ ├── ConflictException
│ ├── RenderException
│ ├── RateLimitException
│ │ └── QuotaExceededException
│ └── ServerException
├── ConnectionException
│ └── TimeoutException
├── DocumentFailedException
├── WaitTimeoutException
└── WebhookVerificationExceptionThe class follows Druckling's error code first, then the HTTP status:
| Exception | When |
|---|---|
ValidationException | 422 schema_validation_failed (data doesn't match the schema) or validation_failed (for example an unknown language, a format the template can't produce, or a broken e-invoice business rule), and 400 malformed requests (bad_request). |
AuthenticationException | 401 unauthorized: missing, invalid or revoked API key. |
PermissionDeniedException | 403 forbidden: the key lacks a permission, for example a Render only key reading templates or managing webhooks. |
NotFoundException | 404 not_found: unknown document, template, webhook endpoint or editor session, or a template without a published version. |
ConflictException | 409 conflict or invalid_state: the resource's current state doesn't allow the request. |
RenderException | render_failed (422) or render_timeout (504): the template couldn't be rendered, or took too long. |
RateLimitException | 429 rate_limited, after the automatic retries. |
QuotaExceededException | 429 quota_exceeded: the plan's document quota is used up. Never retried. |
ServerException | Any other 5xx. |
ApiException | Any other HTTP error (such as 413 payload_too_large), a failed download from a signed URL (download_failed), or a successful response that isn't JSON (invalid_response). |
ConnectionException | No HTTP response: DNS, TLS or network failure. TimeoutException when the built-in transport timed out. |
DocumentFailedException | wait() or a download found the document failed or expired. $e->document holds it. |
WaitTimeoutException | wait() ran out of time. $e->document is the last state seen. |
WebhookVerificationException | A webhook's signature, timestamp or body didn't verify. |
An ApiException has getMessage(), getCode() (the HTTP status) and these readonly properties:
| Property | Type | Notes |
|---|---|---|
status | int | HTTP status. |
errorCode | string | Druckling's error code, for example schema_validation_failed. See Errors. |
field | ?string | Dotted path of the offending field, for example customer.name or language. |
errors | list<FieldError> | Every offending field, with field, message and rule (a broken e-invoice business rule such as BR-CO-25, else null). |
documentId | ?string | The failed document recorded for a payload that didn't validate. |
retryAfter | ?float | Seconds from the response's Retry-After header, when it has one. |
requestId | ?string | Quote it when you contact support. |
body | array, string or null | Decoded JSON body, or the raw text when it isn't JSON. |
headers | array<string, string> | Response headers, with lowercase names. |
ValidationException::messagesByField() groups the messages by field, for showing them next to form inputs.
use Druckling\Exception\ApiException;
use Druckling\Exception\QuotaExceededException;
use Druckling\Exception\RateLimitException;
use Druckling\Exception\ValidationException;
try {
$druckling->documents->create(template: 'invoice-standard', data: ['customer' => ['name' => 'Northwind Ltd.']]);
} catch (ValidationException $e) {
echo $e->getMessage(), PHP_EOL; // Required field invoice was missing from the request payload
foreach ($e->errors as $error) {
echo "{$error->field}: {$error->message}", PHP_EOL;
}
// invoice: missing required field invoice
// line_items: missing required field line_items
// totals: missing required field totals
// customer.address: missing required field customer.address
$e->messagesByField(); // ['invoice' => ['missing required field invoice'], 'line_items' => [...], …]
$e->documentId; // pdf_… (the failed document is kept for your logs)
} catch (QuotaExceededException $e) {
notifyBilling($e->getMessage());
} catch (RateLimitException $e) {
requeueLater($invoice);
} catch (ApiException $e) {
error_log("Druckling {$e->status} {$e->errorCode}: {$e->getMessage()} ({$e->requestId})");
}Catch QuotaExceededException before RateLimitException, since it's a subclass.
Retries and timeouts
The client retries failed requests up to maxRetries times (default 2):
429 rate_limitedis retried for every request, including renders: a rate-limited request produced no file.429 quota_exceededis never retried; you get aQuotaExceededExceptionright away.408,5xx, timeouts and connection errors are retried forGETandDELETErequests only, including downloads from signed URLs.POSTrequests (documents->create(),webhookEndpoints->create(),embedSessions->create()) aren't retried after a5xx, a timeout or a connection error. The API has no idempotency keys yet, so a retry could render the document twice and count twice toward your quota. CatchServerExceptionandConnectionExceptionand decide yourself, for example by checkingdocuments->list()first.
Waits grow exponentially (0.5 s, 1 s, 2 s, … up to 8 s) with jitter. When a response carries a Retry-After header of up to 60 seconds, the SDK waits that long instead; a longer one is thrown to you without retrying. The SDK waits with usleep(), so retries block the process.
With the built-in transport, timeout (default 60 seconds) limits each attempt as a whole, and connecting is limited to 10 seconds. Synchronous renders happen inside the request, so leave room for large documents, or render them with async: true. With a PSR-18 client, its own timeouts apply.
Webhooks
Druckling can call your HTTPS endpoint when a document is rendered, fails or expires. Deliveries follow the Standard Webhooks spec: webhook-id, webhook-timestamp and webhook-signature headers, signed with HMAC-SHA256 over the raw body.
Verify signatures
Webhook::verify() checks the signature and the timestamp, then returns a typed WebhookEvent. Pass the raw body, before any JSON decoding; re-encoded JSON won't match the signature.
<?php
require __DIR__ . '/vendor/autoload.php';
use Druckling\Exception\WebhookVerificationException;
use Druckling\Model\WebhookEvent;
use Druckling\Webhook;
try {
$event = Webhook::verify(file_get_contents('php://input'), getallheaders(), (string) getenv('DRUCKLING_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $e) {
http_response_code(400);
exit;
}
if ($event->type === WebhookEvent::DOCUMENT_RENDERED && $event->document !== null) {
saveInvoice($event->document->id, $event->document->url);
}
http_response_code(204);In Laravel, register the route outside the web middleware group, for example in routes/api.php, so CSRF protection doesn't reject Druckling's requests. In Symfony, use $request->getContent() and $request->headers->all() the same way; with a PSR-7 request, (string) $request->getBody() and $request->getHeaders().
Webhook::verify(string $rawBody, array $headers, string $secret, int $tolerance = 300, ?int $now = null):
| Parameter | Notes |
|---|---|
$rawBody | The raw request body. |
$headers | getallheaders(), $_SERVER (HTTP_WEBHOOK_ID …), a PSR-7 getHeaders() array, or Symfony and Laravel's $request->headers->all(). Names are matched case-insensitively. |
$secret | The endpoint's whsec_… signing secret. |
$tolerance | Maximum age and clock skew of webhook-timestamp, in seconds. Default 300. |
$now | Unix time to check against, for tests. |
The WebhookEvent has id, object, type, createdAt (DateTimeImmutable), testMode, data (the raw data array) and document: a Document for document.rendered, document.failed and document.expired, otherwise null (isDocumentEvent() checks it). The constants WebhookEvent::DOCUMENT_RENDERED, DOCUMENT_FAILED, DOCUMENT_EXPIRED and WEBHOOK_PING name the types.
- Duplicates: a delivery can arrive more than once. Use
$event->id(the same as thewebhook-idheader) to ignore repeats; a resent event keeps its ID. - Answer fast: respond with a
2xxwithin 10 seconds and do slow work in a queue. Other answers and timeouts are retried for about 8.6 hours. Don't answer410 Goneunless you want Druckling to stop: it disables the endpoint. - Secret rotation: after you rotate a secret in the dashboard, deliveries are signed with the new and the old secret for 24 hours. Verification passes with either, so deploy the new secret within that window.
- Test events: Send test event on Developers › Webhooks delivers a
webhook.pingevent;$event->datais['object' => 'ping', 'endpoint_id' => …, 'message' => …]and$event->documentisnull. - Batches:
batch.completedevents verify like any other;$event->documentisnulland$event->datais the batch. There's no constant for it yet: compare$event->typewith'batch.completed'.
Webhook::verifySignature() takes the same arguments and checks the signature without decoding the body. To test your handler, Webhook::sign($secret, $msgId, $timestamp, $body) returns the webhook-signature value Druckling would send ($timestamp in Unix seconds).
Manage webhook endpoints
Managing endpoints needs a Full access key. Endpoints belong to the key's mode: one created with a test key receives only test-mode events.
use Druckling\Model\WebhookEvent;
$endpoint = $druckling->webhookEndpoints->create(
url: 'https://example.com/webhooks/druckling',
events: [WebhookEvent::DOCUMENT_RENDERED, WebhookEvent::DOCUMENT_FAILED],
description: 'Invoice mailer',
);
echo $endpoint->id, ' ', $endpoint->secret; // whe_… whsec_…
foreach ($druckling->webhookEndpoints->list() as $e) {
echo $e->id, ' ', $e->url, ' ', implode(',', $e->events), PHP_EOL;
}
$druckling->webhookEndpoints->get($endpoint->id);
$druckling->webhookEndpoints->delete($endpoint->id); // DeletedObject with ->deleted === trueThe secret is returned only by create(): store it now, for example as DRUCKLING_WEBHOOK_SECRET. The URL must be a public https:// URL. See Webhooks for the event payloads and delivery details, and the webhook endpoint reference for every field.
Embedded editor sessions
Let your users edit a template inside your product with Druckling's white-label editor. Allow your app's origin in Settings › Embed first. Then, when a signed-in user opens the editor, your backend creates a short-lived session with a Full access key and hands its url to that user's browser:
use Druckling\Druckling;
$druckling = new Druckling();
// Your endpoint, e.g. POST /template-editor, after your own login check
$session = $druckling->embedSessions->create(
template: 'invoice-standard',
permissions: ['publish' => true],
user: ['id' => (string) $user->id, 'name' => $user->name],
theme: ['mode' => 'system', 'accent' => '#0f766e'],
expiresIn: 1800,
);
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(['url' => $session->url]);| Argument | Default | Notes |
|---|---|---|
template | required | Slug of the template to edit. |
permissions | ['publish' => false, 'assistant' => false] | publish lets the user publish new versions; by default they edit the draft and you publish. assistant offers the AI assistant on plans that include it; the returned $session->permissions->assistant says whether it's on. |
user | none | ['id' => …, 'name' => …]: shown in request logs and on the versions the user publishes. |
theme | ['mode' => 'light'] | mode is light, dark or system; accent is a #rgb or #rrggbb color. |
expiresIn | 1800 | Seconds until the session ends, 60 to 3600. |
In the browser, mount the url with mountEditor from @druckling/embed, or load it in an iframe yourself. See Embedded editor, and the reference for creating and revoking sessions.
- The
urlcarries the session token in its fragment (#token=…). Give it only to the signed-in user's browser; never log, cache or store it. Onlycreate()returns it. $druckling->embedSessions->revoke($session->id)ends a session right away, for example when the user signs out. It returns the session withstatusrevoked(EmbedSession::STATUS_REVOKED) and anullurl. Revoking twice is fine.create()throwsConflictException(invalid_state) until an origin is allowed in Settings › Embed,PermissionDeniedExceptionfor a Render only key,ValidationExceptionfor bad options, andRateLimitExceptionbeyond about 60 sessions a minute per workspace.
Test and live keys
The API key decides the mode of every request:
dr_test_…keys are for development. Test renders are free and never count toward your plan's quota. Documents you list, webhook endpoints and their events stay separate from live data, and every resource hastestModeset totrue.dr_live_…keys are for production. Live renders count toward your plan's quota.
$druckling->isTestMode() tells you which one a client uses. See Test mode.