Search by

gpibarra / whaloc-sdk-php

gpibarra

PHP SDK for the whaloc control-plane API (a local emulator of Meta's WhatsApp Cloud API), built on Saloon.

Package info

github.com/gpibarra/whaloc-sdk-php

pkg:composer/gpibarra/whaloc-sdk-php

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.0 2026-11-14 23:52 UTC

This package is auto-updated.

Last update: 2026-11-21 03:21:32 UTC


README

A PHP SDK for the control-plane API of whaloc, the local emulator of Meta's WhatsApp Cloud API. Built on Saloon 4, framework-agnostic.

whaloc has two surfaces: the Graph API mock your app under test talks to (/v{version}/…, Meta's shapes), and the control plane (/api/*) that drives the emulator — simulating the user side of a chat, moderating templates, moving messages along the status ladder, arming error injection, inspecting the webhook log. This package covers only the control plane, plus decoding of the /api/ws event stream. Point the app under test at the Graph surface; use this SDK from tests and tooling.

Installation

composer require gpibarra/whaloc-sdk-php

Requires PHP 8.5+.

Quick start

use GPIbarra\WhalocSdk\WhalocConnector;

$w = new WhalocConnector('http://whaloc:8080'); // whaloc's root, not /api

if (! $w->health()) {
    throw new RuntimeException('whaloc is not up');
}

$state = $w->state()->get();
$phone = $state->phoneNumbers()[0];

// A user writes to your business number…
$message = $w->inbound()->text($phone->id, '5571990000001', 'Hi! Is my order ready?', profileName: 'Ana Souza');

// …your app answers through the Graph API, then you assert on the conversation.
$page = $w->conversations()->messages($message->conversationId());

The constructor takes an optional second argument, array $headers, sent with every request. The control plane has no authentication of its own.

Errors

Every non-2xx answer throws GPIbarra\WhalocSdk\Exceptions\WhalocException (a Saloon RequestException). It exposes whaloc's error body, {"error":{"message","code"}}:

use GPIbarra\WhalocSdk\Exceptions\WhalocException;

try {
    $w->templates()->approve('1');
} catch (WhalocException $e) {
    $e->status();           // 404
    $e->errorCode;          // "unknown_template" (null when whaloc sent none)
    $e->errorMessage;       // "no template with ID 1"
    $e->isNotFound();       // also isConflict() (409) and isValidationError() (400)
}

health() is the only method that never throws: an unreachable or failing whaloc is false.

Data objects

Responses are mapped to readonly DTOs under GPIbarra\WhalocSdk\Data. Each one has a static fromArray() and keeps the object exactly as whaloc sent it in $raw, so fields a newer whaloc adds are never lost. Timestamps are ISO 8601 strings; enumerated fields (status, direction, quality…) are plain strings, so a value this SDK does not know yet cannot break decoding. Backed enums under GPIbarra\WhalocSdk\Enums cover every closed set the spec defines, and every method that takes such a value accepts either the enum or its string.

Resources

State and reset

$state = $w->state()->get();      // Data\State: publicUrl, app, wabas (with phoneNumbers), behavior, webhook
$state->phoneNumbers();           // every number of every WABA, flattened
$state->behavior->deliveredDelayMs;
$state->webhook->url;

$fresh = $w->state()->reset();    // back to WHALOC_SEED; returns the new Data\State

Snapshots

$json = $w->snapshots()->export();                          // raw JSON string — keep it a string
$json = $w->snapshots()->export(includeDeliveries: true);   // with the webhook delivery log

$result = $w->snapshots()->import($json);                   // Data\ImportResult: summary + state
$result->summary->counts['messages'];

$w->snapshots()->importFile(fopen('scenario.json', 'r'), 'scenario.json'); // multipart upload

WABAs

$wabas = $w->wabas()->list();                               // list<Data\Waba>
$waba = $w->wabas()->create('Acme', id: '1234567890');      // explicit ID optional
$w->wabas()->update($waba->id, 'Acme Inc');
$w->wabas()->delete($waba->id);                             // returns the deleted Data\Waba

Phone numbers

use GPIbarra\WhalocSdk\Enums\QualityRating;

$numbers = $w->phoneNumbers()->list();                      // list<Data\PhoneNumber>
$numbers = $w->phoneNumbers()->list(wabaId: $waba->id);     // filtered client-side

$number = $w->phoneNumbers()->create($waba->id, '+1 555 010 0200', 'Acme Support', id: '9876543210');
$w->phoneNumbers()->update($number->id, verifiedName: 'Acme Help');
$w->phoneNumbers()->updateBusinessProfile($number->id, ['about' => 'We sell things', 'websites' => ['https://acme.test']]);
$w->phoneNumbers()->quality($number->id, QualityRating::Red, emitWebhook: true, event: 'DOWNGRADE', currentLimit: 'TIER_1K');
$w->phoneNumbers()->delete($number->id);                    // returns the deleted Data\PhoneNumber

Contacts

$contacts = $w->contacts()->list();                         // list<Data\Contact>
$w->contacts()->create('5571990000009', 'Carla Dias', userId: 'BR.CarlaDias01');
$w->contacts()->update('5571990000009', profileName: 'Carla D.');
$w->contacts()->update('5571990000009', clearUserId: true); // removes the BSUID
$w->contacts()->changeNumber('5571990000009', '5571990000010', phoneNumberId: $phone->id);

Conversations

use GPIbarra\WhalocSdk\Data\Conversation;

$conversations = $w->conversations()->list(phoneNumberId: $phone->id); // list<Data\Conversation>

$id = Conversation::idFor($phone->id, '5571990000001');    // "<phoneNumberId>:<waId>"
$page = $w->conversations()->messages($id, limit: 50);      // Data\MessagePage, newest last
while ($page->hasMore()) {
    $page = $w->conversations()->messages($id, limit: 50, before: $page->before);
}

A Data\Message exposes id (the wamid), direction, phoneNumberId, contactWaId, type, payload (Meta's snake_case node), status, error, replyTo, timestamp, templateSnapshot, bizOpaqueCallbackData, createdAt, updatedAt and raw, plus the helpers isInbound(), isOutbound(), content(), text(), mediaId() and conversationId().

Inbound (the user side)

Every helper returns the stored Data\Message. They all accept profileName, replyTo (a wamid, which becomes the message's context) and a final array $extra merged into the body — for timestamp and the context riders forwarded, frequentlyForwarded, referredProduct and referral.

$in = $w->inbound();

$in->text($phone->id, $from, 'Hello');
$in->buttonReply($phone->id, $from, 'btn-yes', 'Yes', replyTo: $outboundWamid);
$in->listReply($phone->id, $from, 'row-1', 'Option 1', description: 'First');
$in->button($phone->id, $from, payload: 'STOP', text: 'Stop promotions');   // template quick reply
$in->location($phone->id, $from, -23.5505, -46.6333, name: 'São Paulo');
$in->reaction($phone->id, $from, $outboundWamid, '👍');
$in->contacts($phone->id, $from, [['name' => ['formatted_name' => 'Carla'], 'phones' => [['phone' => '+5571990000003']]]]);
$in->unsupported($phone->id, $from, 'poll_creation');

// Media: uploads through POST /api/inbound-media, then sends POST /api/inbound.
$in->media($phone->id, $from, 'image', fopen('cat.jpg', 'r'), 'cat.jpg', 'image/jpeg', caption: 'Look');
$in->media($phone->id, $from, 'audio', $bytes, 'note.ogg', 'audio/ogg', extra: ['media' => ['voice' => true]]);

// The two steps on their own:
$upload = $in->uploadMedia($phone->id, $bytes, 'invoice.pdf', 'application/pdf');   // Data\InboundMedia
$in->mediaById($phone->id, $from, 'document', $upload->id, filename: 'invoice.pdf');

// Anything else, as a raw POST /api/inbound body:
$in->send(['phoneNumberId' => $phone->id, 'from' => $from, 'type' => 'text', 'text' => ['body' => 'raw']]);

Messages

use GPIbarra\WhalocSdk\Enums\MessageStatus;

$w->messages()->setStatus($wamid, MessageStatus::Read);
$w->messages()->setStatus($wamid, 'failed', errorCode: 131026);
$presets = $w->messages()->errorPresets();                  // list<Data\MessageErrorPreset>

Media and uploads

$descriptor = $w->media()->get($mediaId);                   // Data\MediaDescriptor: id, url, mimeType, sha256, fileSize

$response = $w->media()->download($mediaId);                // Saloon Response, body streamed
file_put_contents('out.png', $response->body());            // or read $response->stream() in chunks

$upload = $w->uploads()->get($handle);                      // Data\UploadDescriptor (resumable-upload handle)
$w->uploads()->download($handle);

The descriptor url is built from WHALOC_PUBLIC_URL, which may name a host only reachable inside a compose network. download() therefore requests only the URL's path and query, against the connector's own base URL.

Typing indicators

$indicators = $w->typing()->list(phoneNumberId: $phone->id); // list<Data\TypingIndicator>

Templates

use GPIbarra\WhalocSdk\Enums\TemplateStatus;

$templates = $w->templates()->list(['wabaId' => $waba->id, 'status' => TemplateStatus::Pending, 'search' => 'order']);

$w->templates()->approve($id);
$w->templates()->reject($id, 'PROMOTIONAL', ['reason' => 'Too salesy', 'recommendation' => 'Tone it down']);
$w->templates()->pause($id);
$w->templates()->disable($id);
$w->templates()->quality($id, 'YELLOW');

Webhooks

$page = $w->webhooks()->deliveries(limit: 20);              // Data\WebhookDeliveryPage, newest first
$older = $w->webhooks()->deliveries(limit: 20, before: $page->before);

$w->webhooks()->redeliver($page->data[0]->id);              // list<Data\WebhookDelivery>
$w->webhooks()->handshake();                                // Data\HandshakeResult
$w->webhooks()->raw(['object' => 'whatsapp_business_account', 'entry' => [/* … */]]);
$w->webhooks()->accountUpdate($waba->id, 'ACCOUNT_RESTRICTION', restrictionInfo: [
    ['restrictionType' => 'RESTRICTED_BIZ_INITIATED_MESSAGING', 'expiration' => '2026-12-01'],
]);
$w->webhooks()->businessCapabilityUpdate($waba->id, maxDailyConversationPerPhone: 1000, maxPhoneNumbersPerBusiness: 2);

Data\WebhookDelivery::payload() decodes the exact body that was signed and sent.

Error injection

$rule = $w->injectionRules()->create([
    'target' => 'messages.send',
    'trigger' => ['kind' => 'next', 'count' => 2],
    'preset' => 'rate_limit_429',
    'retryAfterSeconds' => 30,
]);

$w->injectionRules()->list();                               // list<Data\InjectionRule>
$w->injectionRules()->delete($rule->id);                    // returns the deleted rule

Tokens

$tokens = $w->tokens()->list();                             // list<Data\TokenState> (empty without WHALOC_TOKENS)
$registry = $w->tokens()->registry();                       // Data\TokenRegistry: strict + tokens
$w->tokens()->expire($tokens[0]->id);                       // the token now gets 401 / 190 / 463
$w->tokens()->restore($tokens[0]->id);

WebSocket events

The SDK does not open the socket — use any WebSocket client on ws://whaloc:8080/api/ws — but it decodes the frames into typed events:

use GPIbarra\WhalocSdk\Data\Events\MessageCreated;
use GPIbarra\WhalocSdk\Data\Events\MessageStatusChanged;
use GPIbarra\WhalocSdk\Data\Events\WsEvent;
use GPIbarra\WhalocSdk\Enums\WsEventType;

$event = WsEvent::fromJson($frame);

match (true) {
    $event->payload instanceof MessageCreated => handleMessage($event->payload->message),
    $event->payload instanceof MessageStatusChanged => handleStatus($event->payload->message, $event->payload->previousStatus),
    $event->is(WsEventType::StateReset), $event->is(WsEventType::StateImported) => reloadEverything(),
    default => null,
};

All twelve event types have a payload class: MessageCreated{message}, MessageStatusChanged{message, previousStatus}, TypingChanged{typing}, TemplateChanged{template, event}, WebhookDeliveryLogged{delivery}, ContactChanged{contact, previousWaId}, WabaChanged{waba, event}, PhoneNumberChanged{phoneNumber, event}, InjectionChanged{rule, event}, TokenChanged{token}, StateReset{state} and StateImported{state}. An event type this SDK does not know yet decodes with type === null, the original string in $event->name, and an UnknownPayload holding the raw payload — it never throws.

Testing

Unit tests use Saloon's MockClient with fixtures captured from a real whaloc (tests/Fixtures), one test per endpoint:

composer install
composer test           # Pest
composer analyse        # PHPStan, level 8
composer format:check   # Pint (composer format to fix)

The integration suite in tests/Integration runs the SDK against a live whaloc and is skipped unless WHALOC_TEST_URL is set. It resets that whaloc before and after every test, so never point it at an instance whose state you care about:

WHALOC_TEST_URL=http://localhost:8080 composer test

In your own tests, fake the connector the Saloon way:

use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;

$w = new WhalocConnector('http://whaloc.test');
$w->withMockClient(new MockClient([MockResponse::make(['status' => 'ok'])]));

Spec sources

The SDK follows whaloc's control-plane contract at tag v0.2.0: docs/SPEC.md (§5) and the zod schemas in packages/shared. They are vendored in resources/spec, with links to the upstream files, as reference material only; they are excluded from the Composer dist archive.

License

MIT