Skip to main content

PHP SDK

The official TurboDocx Deliverable SDK for PHP applications. Generate documents from templates with dynamic variable injection, download source files and PDFs, and manage deliverables programmatically. Available on Packagist as turbodocx/sdk.

Installation

composer require turbodocx/sdk

Requirements

  • PHP 8.1 or higher
  • Composer
  • ext-json
  • ext-fileinfo
Modern PHP Features

This SDK leverages PHP 8.1+ features including enums, named parameters, readonly classes, and match expressions for a superior developer experience.


Configuration

<?php

use TurboDocx\Deliverable;
use TurboDocx\Config\DeliverableConfig;

// Configure with all options
Deliverable::configure(new DeliverableConfig(
apiKey: $_ENV['TURBODOCX_API_KEY'], // Required: Your TurboDocx API key
orgId: $_ENV['TURBODOCX_ORG_ID'], // Required: Your organization ID
baseUrl: 'https://api.turbodocx.com' // Optional: Custom API endpoint
));
No senderEmail Required

Unlike TurboSign, the Deliverable module only requires apiKey and orgId — no sender email or name is needed.

Environment Variables

# .env
TURBODOCX_API_KEY=your_api_key_here
TURBODOCX_ORG_ID=your_org_id_here
API Credentials Required

Both apiKey and orgId parameters are required for all API requests. To get your credentials, follow the Get Your Credentials steps from the SDKs main page.


Quick Start

Generate a document from a template

<?php

use TurboDocx\Deliverable;
use TurboDocx\Config\DeliverableConfig;

Deliverable::configure(DeliverableConfig::fromEnvironment());

// Generate a document from a template with variables
$result = Deliverable::generateDeliverable([
'name' => 'Q1 Report',
'templateId' => 'your-template-id',
'variables' => [
['placeholder' => '{CompanyName}', 'text' => 'Acme Corporation', 'mimeType' => 'text'],
['placeholder' => '{Date}', 'text' => '2026-03-12', 'mimeType' => 'text'],
],
'description' => 'Quarterly business report',
'tags' => ['reports', 'quarterly'],
]);

echo "Deliverable ID: {$result['results']['deliverable']['id']}\n";
Always Handle Errors

The above examples omit error handling for brevity. In production, wrap all Deliverable calls in try-catch blocks. See Error Handling for complete patterns.

Download and manage deliverables

<?php

use TurboDocx\Deliverable;

// List deliverables with pagination
$list = Deliverable::listDeliverables(['limit' => 10, 'showTags' => true]);
echo "Total: {$list['totalRecords']}\n";

// Get deliverable details
$details = Deliverable::getDeliverableDetails('deliverable-uuid', showTags: true);
echo "Name: {$details['name']}\n";

// Download source file (DOCX/PPTX)
$sourceFile = Deliverable::downloadSourceFile('deliverable-uuid');
file_put_contents('report.docx', $sourceFile);

// Download PDF
$pdfFile = Deliverable::downloadPDF('deliverable-uuid');
file_put_contents('report.pdf', $pdfFile);

// Update deliverable
$updated = Deliverable::updateDeliverableInfo('deliverable-uuid', [
'name' => 'Q1 Report - Final',
'description' => 'Final quarterly business report',
]);

// Delete deliverable
$deleted = Deliverable::deleteDeliverable('deliverable-uuid');
Always Handle Errors

The above examples omit error handling for brevity. In production, wrap all Deliverable calls in try-catch blocks. See Error Handling for complete patterns.


Variable Types

The Deliverable module supports four variable types for template injection:

1. Text Variables

Inject plain text values into template placeholders:

$variables = [
['placeholder' => '{CompanyName}', 'text' => 'Acme Corporation', 'mimeType' => 'text'],
['placeholder' => '{Date}', 'text' => '2026-03-12', 'mimeType' => 'text'],
];

2. HTML Variables

Inject rich HTML content with formatting:

$variables = [
[
'placeholder' => '{Summary}',
'text' => '<p>This is a <strong>formatted</strong> summary with <em>rich text</em>.</p>',
'mimeType' => 'html',
],
];

3. Image Variables

Inject images by providing a URL or base64-encoded content:

$variables = [
[
'placeholder' => '{Logo}',
'text' => 'https://example.com/logo.png',
'mimeType' => 'image',
],
];

4. Markdown Variables

Inject markdown content that gets converted to formatted text:

$variables = [
[
'placeholder' => '{Notes}',
'text' => "## Key Points\n- First item\n- Second item\n\n**Important:** Review before submission.",
'mimeType' => 'markdown',
],
];
Variable Stack

For repeating content (e.g., table rows), use variableStack instead of text to provide multiple values for the same placeholder. See the PHP Types section for details.


API Reference

Configure

Configure the SDK with your API credentials and organization settings.

use TurboDocx\Deliverable;
use TurboDocx\Config\DeliverableConfig;

// Manual configuration
Deliverable::configure(new DeliverableConfig(
apiKey: 'your-api-key',
orgId: 'your-org-id'
));

// Or from environment
Deliverable::configure(DeliverableConfig::fromEnvironment());

Generate deliverable

Generate a new document from a template with variable substitution.

$result = Deliverable::generateDeliverable([
'name' => 'Q1 Report',
'templateId' => 'your-template-id',
'variables' => [
['placeholder' => '{CompanyName}', 'text' => 'Acme Corp', 'mimeType' => 'text'],
['placeholder' => '{Date}', 'text' => '2026-03-12', 'mimeType' => 'text'],
],
'description' => 'Quarterly business report',
'tags' => ['reports', 'quarterly'],
]);

echo "Deliverable ID: {$result['results']['deliverable']['id']}\n";

List deliverables

List deliverables with pagination, search, and filtering.

$list = Deliverable::listDeliverables([
'limit' => 10,
'offset' => 0,
'query' => 'report',
'showTags' => true,
]);

echo "Total records: {$list['totalRecords']}\n";
foreach ($list['results'] as $deliverable) {
echo " {$deliverable['name']}\n";
}

Get deliverable details

Retrieve the full details of a single deliverable, including variables and fonts.

$details = Deliverable::getDeliverableDetails('deliverable-uuid', showTags: true);

echo "Name: {$details['name']}\n";
echo "Template: {$details['templateName']}\n";
echo "Created: {$details['createdOn']}\n";

Update deliverable info

Update a deliverable's name, description, or tags.

$result = Deliverable::updateDeliverableInfo('deliverable-uuid', [
'name' => 'Q1 Report - Final',
'description' => 'Final quarterly business report',
'tags' => ['reports', 'final'],
]);

echo "Updated: {$result['deliverableId']}\n";

Delete deliverable

Soft-delete a deliverable.

$result = Deliverable::deleteDeliverable('deliverable-uuid');

echo "Deleted: {$result['deliverableId']}\n";
echo "Message: {$result['message']}\n";

Download source file

Download the original source file (DOCX or PPTX).

$sourceFile = Deliverable::downloadSourceFile('deliverable-uuid');

// Save to file
file_put_contents('report.docx', $sourceFile);

// Or send as HTTP response
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="report.docx"');
echo $sourceFile;

Download PDF

Download the PDF version of a deliverable.

$pdfFile = Deliverable::downloadPDF('deliverable-uuid');

// Save to file
file_put_contents('report.pdf', $pdfFile);

// Or send as HTTP response
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
echo $pdfFile;

Error Handling

The SDK provides typed exceptions for different error scenarios.

Error Classes

Error ClassStatus CodeDescription
TurboDocxExceptionvariesBase exception for all SDK errors
AuthenticationException401Invalid or missing API credentials
ValidationException400Invalid request parameters
NotFoundException404Deliverable or template not found
RateLimitException429Too many requests
NetworkException-Network connectivity issues

Handling Errors

<?php

use TurboDocx\Deliverable;
use TurboDocx\Exceptions\TurboDocxException;
use TurboDocx\Exceptions\AuthenticationException;
use TurboDocx\Exceptions\ValidationException;
use TurboDocx\Exceptions\NotFoundException;
use TurboDocx\Exceptions\RateLimitException;
use TurboDocx\Exceptions\NetworkException;

try {
$result = Deliverable::generateDeliverable([
'name' => 'Q1 Report',
'templateId' => 'your-template-id',
'variables' => [
['placeholder' => '{CompanyName}', 'text' => 'Acme Corp', 'mimeType' => 'text'],
],
]);
} catch (AuthenticationException $e) {
// 401 - Invalid API key or access token
echo "Authentication failed: {$e->getMessage()}\n";
} catch (ValidationException $e) {
// 400 - Invalid request data
echo "Validation error: {$e->getMessage()}\n";
} catch (NotFoundException $e) {
// 404 - Deliverable or template not found
echo "Not found: {$e->getMessage()}\n";
} catch (RateLimitException $e) {
// 429 - Rate limit exceeded
echo "Rate limit: {$e->getMessage()}\n";
} catch (NetworkException $e) {
// Network/connection error
echo "Network error: {$e->getMessage()}\n";
}

Error Properties

All exceptions extend TurboDocxException and include:

  • getMessage() - Human-readable error message
  • statusCode - HTTP status code (if applicable)
  • errorCode - Error code string (e.g., 'AUTHENTICATION_ERROR')

PHP Types

Variable Array Structure

Variables are passed as associative arrays with the following keys:

KeyTypeRequiredDescription
placeholderstringYesTemplate placeholder (e.g., {CompanyName})
textstringNo*Value to inject
mimeTypestringYes"text", "html", "image", or "markdown"
isDisabledboolNoSkip this variable during generation
subvariablesarrayNoNested sub-variables for HTML content
variableStackarrayNoMultiple instances for repeating content
aiPromptstringNoAI prompt for content generation (max 16,000 chars)

*Required unless variableStack is provided or isDisabled is true.

Generate Deliverable Request

Request array for generateDeliverable:

KeyTypeRequiredDescription
namestringYesDeliverable name (3-255 characters)
templateIdstringYesTemplate ID to generate from
variablesarrayYesVariables for template substitution
descriptionstringNoDescription (up to 65,535 characters)
tagsarrayNoTag strings to associate

Update Deliverable Request

Request array for updateDeliverableInfo:

KeyTypeRequiredDescription
namestringNoUpdated name (3-255 characters)
descriptionstringNoUpdated description
tagsarrayNoReplace all tags (empty array to remove)

List Deliverables Options

Options array for listDeliverables:

KeyTypeRequiredDescription
limitintNoResults per page (1-100, default 6)
offsetintNoResults to skip (default 0)
querystringNoSearch query to filter by name
showTagsboolNoInclude tags in the response

Deliverable Record

The deliverable record returned by listDeliverables:

KeyTypeDescription
idstringUnique deliverable ID (UUID)
namestringDeliverable name
descriptionstringDescription text
templateIdstringSource template ID
createdBystringUser ID of the creator
emailstringCreator's email address
fileSizeintFile size in bytes
fileTypestringMIME type of the generated file
defaultFontstringDefault font used
fontsarrayFonts used in the document
isActiveboolWhether the deliverable is active
createdOnstringISO 8601 creation timestamp
updatedOnstringISO 8601 last update timestamp
tagsarrayAssociated tags (when showTags=true)

Deliverable Detail Record

The deliverable record returned by getDeliverableDetails. Includes all fields from Deliverable Record except fileSize, plus:

KeyTypeDescription
templateNamestringSource template name
templateNotDeletedboolWhether the source template still exists
variablesarrayParsed variable objects with values

Tag

Tag object included when showTags is enabled. Each tag is an associative array with:

KeyTypeDescription
idstringTag unique identifier (UUID)
labelstringTag display name
isActiveboolWhether the tag is active
updatedOnstringISO 8601 last update timestamp
createdOnstringISO 8601 creation timestamp
createdBystringUser ID of the tag creator
orgIdstringOrganization ID

Additional Documentation

For detailed information about advanced configuration and API concepts, see:

Core API References


Resources