PHPMenu
On this page

PHP

Integrate with the Kirora API using the PHP library: response models, automatic pagination, retries and webhook verification.

View as MarkdownOpen in ClaudeOpen in ChatGPTUpdated

Identify contacts, track events and send transactional messages from your PHP app with the kirora/kirora-php package. It calls the Kirora /v1 API with response models, pagination, retry handling and webhook verification. It works with any framework, or none; for Laravel, the Laravel package adds a configured client, a facade and webhook events on top of it. This page covers the common tasks; the usage guide is the full reference.

Install

Add the package with Composer:

Terminal
composer require kirora/kirora-php

It needs PHP 8.1 or later. It sends requests with Guzzle by default, or with any PSR-18 client you give it.

Create a client

Keep your API key on your server and set it as KIRORA_API_KEY. Kirora::client() reads it from there:

PHP
$kirora = Kirora::client(); // reads KIRORA_API_KEY

Kirora is a global class: in namespaced code, write \Kirora::client() or import it. The client checks getenv() first, then $_ENV and $_SERVER. It doesn’t load .env files, so if your framework keeps its configuration elsewhere, pass the key as the first argument.

Create one client and reuse it for the whole request or worker. The second argument takes its options:

Option Default Description
baseUrl KIRORA_BASE_URL, or https://api.kirora.io For tests and mocks. The host only, without a version: the client adds /v1 to each path.
timeout 30 Seconds each attempt may take, including reading the response.
maxRetries 3 Attempts after the first, from 0 to 10. 0 disables retrying.
maxRetryDelay 30 The longest single wait between attempts, in seconds. A longer Retry-After stops retrying.
httpClient A new Guzzle client Any PSR-18 client, such as a Guzzle client with a proxy or middleware.
workspace None Partner keys only: the tenant workspace’s externalId. See Partner workspaces.
headers None Extra headers on every request.
appInfo None ['name' => ..., 'version' => ...], added to the User-Agent.
PHP
$kirora = Kirora::client(null, ['maxRetries' => 5]);

An unknown option throws an InvalidArgumentException, so a typo can’t pass unnoticed. timeout applies when the client is Guzzle; set the timeout on any other PSR-18 client yourself.

Each resource is a service on the client: $kirora->contacts, $kirora->events, $kirora->transactional, $kirora->campaigns, $kirora->segments, $kirora->lists, $kirora->messages, $kirora->suppressions, and, for partner keys, $kirora->workspaces and $kirora->embedSessions. A contact’s lists, segments, topic preferences and push devices have their own services, such as $kirora->contacts->topics.

$kirora->me() returns the API key in use, its scopes and the workspace it acts in, so it makes a good connection test. $kirora->forWorkspace($externalId) returns a copy that acts in one of your tenants.

Methods that take a contact take Kirora’s id by default. To use your own, pass idType:

PHP
$contact = $kirora->contacts->get('[email protected]', ['idType' => 'email']);

idType is 'email' or 'externalId'. It’s a query, so it comes before the call options; pass [] to skip it: $kirora->contacts->get($contactId, [], ['timeout' => 5]).

Requests and responses

Requests take arrays, shaped as the API reference describes them. In an update, leave a field out to keep its value, and set it to null to clear it:

PHP
$kirora->contacts->update($contactId, [
    'firstName' => 'Olivia',
    'lastName' => null, // clears it
    // phone is left as it is
]);

Responses are read-only models from Kirora\Models. Read a field as a property or an array key, $contact->email or $contact['email']; a field the response doesn’t have reads as null. Each model documents its fields, so your editor completes them. toArray() and toJson() serialize one, and fields newer than your version of the package are kept and read the same way.

Identify a contact

contacts->identify() calls identifyContact: an upsert resolved by externalId, then email, then phone. It is safe to repeat; it converges rather than creating duplicates.

PHP
$contact = $kirora->contacts->identify([
    'externalId' => 'cust_1042',
    'email' => '[email protected]',
    'firstName' => 'Olivia',
]);
echo $contact->id;

Track an event

events->track() calls trackEvent. The idempotency key is optional; pass one derived from your own event or order id to make your own retries safe too. Without one, the library makes one per call, which covers only its own retries.

PHP
$kirora->events->track([
    'externalId' => 'cust_1042',
    'name' => 'Order Completed',
    'properties' => ['order_id' => '1042', 'total' => 42.5, 'currency' => 'USD'],
], ['idempotencyKey' => 'order-1042-completed']);

events->trackBatch() sends up to 100 events at once, each with its own idempotencyKey. One event refused doesn’t stop the rest: the call succeeds, and each entry in results, in the order you sent them, has either the event or an error:

PHP
$batch = $kirora->events->trackBatch(['events' => $entries]);
foreach ($batch->results as $index => $result) {
    if (isset($result['error'])) {
        error_log("Event {$index} not tracked: {$result['error']['code']}");
    }
}

A refusal of the whole batch throws, like any other call. contacts->identifyBatch(), contacts->deleteBatch() and transactional->sendBatch() work the same way.

Send a transactional message

transactional->send() calls sendTransactionalMessage. The key is optional, but pass your own, made once per logical send before the first attempt and outside any retry loop: a retry with the same key and body then replays the first send for as long as its message is kept (Retention). Without one, the library makes one per call, which covers only its own retries. See Idempotency.

PHP
$orderId = '1042';

$sent = $kirora->transactional->send([
    'to' => ['email' => '[email protected]'],
    'data' => ['order_id' => $orderId],
    'email' => ['template' => 'order-receipt'], // its alias or its id
], ['idempotencyKey' => "receipt-{$orderId}"]);

A successful send can still leave a channel unsent, such as push for a contact with no device: each is in $sent->skippedChannels, with its channel and code. A cc or bcc address that got no copy is in $sent->skippedCopies. transactional->cancel($messageId) cancels a message scheduled with sendAt.

Paginate

all() iterates over every item, fetching pages as you go. It fetches nothing until you start, and nothing more once you break:

PHP
foreach ($kirora->contacts->all(['query' => 'olivia']) as $contact) {
    echo $contact->email, "\n";
}

list() fetches one page, and iterating it doesn’t fetch the next. To fetch the next page yourself, pass its cursor back with the same filters. nextCursor() is null on the last page; treat the cursor as opaque.

PHP
$page = $kirora->contacts->list(['query' => 'olivia', 'limit' => 100]);

if ($page->hasMore()) {
    $next = $kirora->contacts->list(['query' => 'olivia', 'limit' => 100, 'cursor' => $page->nextCursor()]);
}

See Pagination.

Errors

Every error the API returns throws a Kirora\Exceptions\ErrorException. Branch on its code with is(), never on the message:

PHP
use Kirora\Enums\ErrorCode;
use Kirora\Exceptions\ErrorException;

try {
    $kirora->campaigns->send($campaignId);
} catch (ErrorException $e) {
    if ($e->is(ErrorCode::SendingDomainUnverified)) {
        // Recoverable: publish the DNS records and check the domain.
    } else {
        error_log("Kirora request failed: {$e->errorCode} (request {$e->requestId})");
        throw $e;
    }
}
Property Description
errorCode The API’s error code, as a string, including codes added after your version of the package. Match a known one with is(ErrorCode::...); isKnownCode() tells you whether your version knows it.
errorMessage Human-readable; for logs, not for branching.
status The HTTP status, also getCode().
errors On VALIDATION_ERROR and DRAFT_INCOMPLETE, each field the request got wrong, with a message to show beside it.
details What else the code reports. Its shape depends on the code; see Errors.
requestId The X-Request-Id response header, for support.
retryAfter The Retry-After header in seconds, when the server sent one.
rateLimit The rate limit headers, when the server sent them.

Other failures throw other exceptions, all implementing Kirora\Exceptions\KiroraException:

  • TransporterException: no complete response, such as a network error, or the connection dropping while the body was read. TimeoutException, a subclass, means an attempt took longer than timeout.
  • UnserializableResponse: a response the library can’t use, such as HTML from a proxy, a redirect or a body over 64 MiB.

An invalid argument, such as an empty id or an unknown option, throws PHP’s InvalidArgumentException before anything is sent.

Retries and timeouts

Every request goes through one retry loop, which repeats a call only when repeating it is safe. Whether an operation is safe to repeat comes from the API’s spec, not from each method:

  • 429 is always retried, as are connections never made, such as a failed DNS lookup: the server did nothing.
  • 5xx and other network failures are retried only when a repeat can’t cause a duplicate: reads, operations that converge on the same result, and writes with an idempotency key, which the library makes per call wherever the endpoint takes one and reuses on each retry.
  • IDEMPOTENCY_KEY_IN_USE (409) is retried when the call has a key: an earlier attempt, such as one that timed out, is still running, and waiting gets its response.
  • Other 4xx errors are never retried, including the other idempotency 409s, IDEMPOTENCY_KEY_REUSED and IDEMPOTENCY_KEY_OUTCOME_UNKNOWN. A delete retried after an attempt that may have done it treats a 404 as success.
  • Backoff: exponential with jitter, capped at maxRetryDelay. When the server sends Retry-After, the retry never comes sooner.
  • Bounded: at most maxRetries retries (default 3), then the last error is thrown. A retry sends the same body and idempotency key as the first attempt.
  • Timeout: timeout (default 30 seconds) applies to each attempt, so a call that retries can take longer in total. PHP can’t cancel a call from outside, so for an overall limit, lower maxRetries or maxRetryDelay.

Per-call options

Every method takes call options as its last argument:

Option Description
idempotencyKey On methods that create, send or record something. Per call only.
workspace Partner keys only: the tenant to act in for this call.
timeout, maxRetries, maxRetryDelay Override the client’s settings for this call.
headers Added to the client’s headers for this call.

Every model and page carries the response it came from as lastResponse(), with its requestId, its rateLimit, and idempotencyReplay, which is true when an earlier request with the same key already did the work and this is its stored response:

PHP
$contact = $kirora->contacts->get($contactId);
echo $contact->lastResponse()->requestId; // quote this to Kirora support

Verify webhooks

Verify each webhook against the raw request body, before decoding it: decoded and re-encoded JSON won’t match the signature. Webhook::verify() checks the signature in constant time, rejects a timestamp more than 5 minutes from now, accepts any of the signatures sent while a secret rotation overlaps, and returns null for a webhook that fails:

PHP
use Kirora\Webhook;

$webhook = Webhook::verify(
    getenv('KIRORA_WEBHOOK_SECRET'),
    file_get_contents('php://input'),
    getallheaders(), // or a PSR-7 request
);
if ($webhook === null) {
    http_response_code(401);
    exit;
}

// Delivery is at-least-once: deduplicate on $webhook->payload['eventId'].
error_log("{$webhook->payload['eventType']} {$webhook->payload['eventId']}");
http_response_code(200);

To find out why one was rejected, call Webhook::assert() instead. It throws a WebhookVerificationException whose reason is InvalidTimestamp, InvalidHeaders, SignatureMismatch (usually the wrong secret, or a body that was decoded first), TimestampOutsideTolerance (a replay, or your server’s clock is out of sync) or BodyTooLarge (over 10 MiB). Pass ['tolerance' => 600] as the last argument to change the replay window.

Record an event as handled only once its work has succeeded, so a failed delivery is handled again on retry. The event types are the cases of Kirora\Enums\WebhookEvent; treat the type as open, because a * subscription receives types added later. See Webhooks.

Partner workspaces

With a partner key, act in one of your tenants’ workspaces by its externalId, with forWorkspace(), or with workspace in the client’s options or a single call’s. Each is sent as the Kirora-Workspace header; a call’s option overrides the client’s. An empty externalId is refused rather than acting in your own workspace.

PHP
$tenant = $kirora->forWorkspace('tenant-42');
$contact = $tenant->contacts->get($contactId);

Manage the workspaces themselves with $kirora->workspaces. delete() takes effect after a grace period, which cancelDeletion() stops.

To embed Kirora’s segment or email builder in your app, create a session for the tenant on your server and give its token to the browser. A session lasts 15 minutes.

PHP
$session = $kirora->forWorkspace('tenant-42')->embedSessions->create(['components' => ['email_builder']]);

Sign tokens for the web SDK

The web SDK signs users in with a token from your server. UserToken::create($secret, $userId) signs one:

PHP
use Kirora\UserToken;

echo UserToken::create(getenv('KIRORA_SDK_TOKEN_SECRET'), (string) $currentUser->id);

$secret is the workspace’s SDK token secret, from Developer → SDK in the dashboard; it never leaves your server. $userId is your own id for the signed-in user, their contact’s externalId, taken from your server’s session, never from the browser. A token lasts an hour; pass a third argument for another lifetime in seconds, up to Kirora’s limit of 24 hours. It needs no client and no API key. The web SDK’s setup has the whole route.

Other endpoints

For an operation without a method, call it through the client, with the same authentication, retries and errors. The path starts with /v1; encode each id in it with rawurlencode(). request() returns the whole decoded body, envelope included, requestData() unwraps its data, and requestAll() pages like the services’ all():

PHP
$segment = $kirora->requestData('GET', '/v1/segments/' . rawurlencode($segmentId));

foreach ($kirora->requestAll('/v1/segments') as $segment) {
    // ...
}

These return arrays rather than models. For a large body, such as an export to stream to a file, requestRaw() returns the PSR-7 response with its body unread. An endpoint newer than your version of the package is retried as a write only if you pass an idempotencyKey.

Test your code

To test code that calls Kirora, give the client a Guzzle client with a MockHandler that answers with canned JSON, and turn retries off so a failure shows at once:

PHP
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

$mock = new MockHandler([
    new Response(200, ['Content-Type' => 'application/json'], '{"data":{"id":"beta","name":"Beta testers"}}'),
]);

$kirora = Kirora::client('test-key', [
    'httpClient' => new Client(['handler' => HandlerStack::create($mock)]),
    'maxRetries' => 0,
]);

echo $kirora->lists->get('beta')->name; // Beta testers

Add Guzzle’s Middleware::history() to the stack to check the requests your code sent.