1. Go to this page and download the library: Download homlity/chat-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
homlity / chat-sdk example snippets
use Homlity\Chat\Enum\Ability;
use Homlity\Chat\Platform\PlatformClient;
$platform = new PlatformClient(
platformSlug: 'codi', // el slug que te asignó Homlity
platformSecret: getenv('CHAT_PLATFORM_SECRET'),
);
$token = $platform->accessTokens()->issue(
accountId: '42', // TU id de cliente (la inmobiliaria)
name: 'Codi - sesión asesor',
abilities: Ability::advisorSession(), // el conjunto mínimo
expiresInMinutes: 15,
userId: '7', // TU id del asesor que actúa
);
return response()->json($token->forBrowser());
use Homlity\Chat\Account\AccountClient;
use Homlity\Chat\Enum\ConversationStatus;
$chat = new AccountClient($tokenQueEmitioTuBackend);
// Iteración perezosa: una petición por página, solo cuando hace falta.
foreach ($chat->conversations()->all(status: ConversationStatus::OPEN) as $conversacion) {
echo $conversacion['uuid'], ' ', $conversacion['contact']['display_name'] ?? '', PHP_EOL;
}
$enviado = $chat->conversations()->sendMessage(
conversationUuid: '550e8400-e29b-41d4-a716-446655440000',
text: 'Hola, soy tu asesor. ¿En qué zona estás buscando?',
takeOver: true, // toma el control en la misma llamada
);
$enviado->clientMessageId; // el SDK lo generó; guárdalo si vas a reintentar
$enviado->isDuplicate; // true si el servicio devolvió el mensaje original (200)
use Homlity\Chat\Enum\WebhookEventType;
$registro = $platform->webhooks()->register(
url: 'https://api.codi.com/hooks/chat', // debe ser https
events: [WebhookEventType::MESSAGE_RECEIVED, WebhookEventType::HANDOFF_REQUESTED],
// scope: WebhookScope::PLATFORM (por defecto)
);
$registro->secret; // ⚠️ llega UNA SOLA VEZ: guárdalo cifrado
use Homlity\Chat\Exception\WebhookVerificationException;
use Homlity\Chat\Webhook\DeliveryDeduplicator;
use Homlity\Chat\Webhook\Store\Psr16DeliveryStore;
use Homlity\Chat\Webhook\WebhookVerifier;
$verificador = new WebhookVerifier($secretoGuardado);
$dedup = new DeliveryDeduplicator(new Psr16DeliveryStore(cache()->store()));
// 1. Cuerpo CRUDO. En PHP puro, php://input.
$cuerpoCrudo = file_get_contents('php://input');
try {
$evento = $verificador->verify($cuerpoCrudo, $_SERVER);
} catch (WebhookVerificationException $e) {
http_response_code(401);
exit;
}
// 2. Deduplica: la entrega es "al menos una vez".
if (! $dedup->firstTime($evento->deliveryId)) {
http_response_code(200);
exit;
}
// 3. Responde 2xx YA y procesa después.
http_response_code(202);
echo '{"ok":true}';
fastcgi_finish_request();
$idDeTuCliente = $evento->accountExternalId(); // con esto enrutas
procesar($evento);
// AppServiceProvider::register()
$this->app->bind(VerifyChatWebhook::class, fn () => new VerifyChatWebhook(
new WebhookVerifier(config('services.chat_homlity.webhook_secret')),
new DeliveryDeduplicator(new Psr16DeliveryStore(cache()->store())),
));
// bootstrap/app.php
->withMiddleware(fn (Middleware $m) => $m->alias(['chat.webhook' => VerifyChatWebhook::class]))
// routes/api.php (en api.php, no en web.php: así no pasa por CSRF)
Route::post('/hooks/chat', ChatWebhookController::class)->middleware('chat.webhook');
final class ChatWebhookController
{
public function __invoke(Request $request): Response
{
$evento = VerifyChatWebhook::eventFrom($request); // ya verificado y deduplicado
ProcesarEventoDeChat::dispatch($evento->type, $evento->payload)->afterResponse();
return response()->noContent();
}
}
$resultado = $platform->webhooks()->test();
echo $resultado->explain();
// "Entregado: tu endpoint respondió 200 en 142 ms. La verificación de firma funciona."
$resultado->matchesLocalSecret($secretoGuardado);
new ClientOptions(maxRetries: 5, retryBaseDelay: 0.5, retryMaxDelay: 8.0);
$firma = $platform->debugSignature(Request::get('/api/v1/conversations')->withTenant('42', '7'));
echo $firma->canonical; // el string canónico exacto que se firmó (no contiene el secreto)
$platform->accessTokens()->issue($accountId, $name, $abilities, $expiresInMinutes, $userId);
$platform->accessTokens()->list($accountId);
$platform->accessTokens()->revoke($accountId, $tokenUuid);
$platform->webhooks()->get($scope);
$platform->webhooks()->register($url, $events, $scope, $accountId);
$platform->webhooks()->disable($scope);
$platform->webhooks()->test(); // diagnóstico
$platform->webhooks()->deliveries($status);
$platform->webhooks()->allDeliveries($status); // iteración perezosa
$platform->webhooks()->retryDelivery($deliveryUuid);
$platform->accountClient($token); // cliente de cuenta para tareas de servidor
$platform->actingAsAccount($accountId, $abilities); // emite y construye en un paso
use Homlity\Chat\Account\AiConfigUpdate;
use Homlity\Chat\Enum\AiTone;
use Homlity\Chat\Enum\AiTool;
$chat->ai()->updateConfig(
AiConfigUpdate::make()
->name('Asistente de Inmobiliaria Norte')
->enabled(true)
->model('claude-sonnet-5')
->apiKey($claveDeLaInmobiliaria) // solo esta vez
->systemInstructions('Responde en español, tutea, no inventes precios.')
->maxResponseLength(1200) // 100–4096, validado en el cliente
->maxToolCallsPerTurn(3) // 0–10
->autoHandoffEnabled(true)
->tone(AiTone::FRIENDLY)
->allowedTools([AiTool::SEARCH_PROPERTIES, AiTool::CREATE_LEAD, AiTool::REQUEST_HUMAN_AGENT])
);
// Borrar la credencial y desactivar el asistente:
$chat->ai()->updateConfig(AiConfigUpdate::make()->removeApiKey());
use Homlity\Chat\Account\Recipient;
$chat->campaigns()->addRecipients($campanaUuid, [
Recipient::optedIn(
phone: '573001112233',
consentedAt: '2026-08-01T10:00:00-05:00',
consentSource: 'web_form',
displayName: 'María',
templateComponents: [['type' => 'body', 'parameters' => [['type' => 'text', 'text' => 'María']]]],
),
// ... tantos como quieras: el SDK trocea en lotes de 500
]);
$pagina = $chat->conversations()->list(perPage: 50);
$pagina->data; $pagina->currentPage; $pagina->lastPage; $pagina->total;
$pagina->hasMorePages();
// Iteración perezosa sobre elementos, atravesando páginas:
foreach ($chat->conversations()->all() as $conversacion) { /* ... */ }
// O página a página:
foreach ($chat->conversations()->all()->pages() as $pagina) { /* ... */ }
$chat->realtime()->stream(function (array $evento): bool {
// procesa
return true; // devolver false corta la escucha
}, afterId: $ultimoIdConocido);
use Homlity\Chat\Enum\ConversationStatus; // open, pending, resolved, closed, spam
use Homlity\Chat\Enum\ConversationMode; // ai, waiting_human, human, paused
use Homlity\Chat\Enum\MessageDirection; // inbound, outbound
use Homlity\Chat\Enum\MessageSenderType; // customer, ai, human, system
use Homlity\Chat\Enum\MessageType; // text, image, audio, video, document, ...
use Homlity\Chat\Enum\MessageStatus; // received, pending, sending, sent, ...
use Homlity\Chat\Enum\Ability; // permisos de token
use Homlity\Chat\Enum\WebhookEventType;
use Homlity\Chat\Enum\AiTool;
use Homlity\Chat\Enum\AiTone;
use Homlity\Chat\Enum\KnowledgeType;
ConversationStatus::isKnown($conversacion['status']);
use Homlity\Chat\Http\ClientOptions;
$options = new ClientOptions(
connectTimeout: 5.0, // segundos
timeout: 15.0,
maxRetries: 3,
retryBaseDelay: 0.5,
retryMaxDelay: 8.0,
httpClient: null, // cualquier HttpClientInterface, p. ej. Psr18HttpClient
userAgentSuffix: 'codi-web/2.4',
);
$platform = new PlatformClient('codi', $secreto, options: $options);
use Homlity\Chat\Http\Psr18HttpClient;
$options = new ClientOptions(
httpClient: new Psr18HttpClient($guzzle, $requestFactory, $streamFactory),
);
use Homlity\Chat\Http\ClientOptions;
use Homlity\Chat\Http\HttpClientInterface;
use Homlity\Chat\Http\Response;
final class ClienteFalso implements HttpClientInterface
{
public function send(string $method, string $url, array $headers, string $body): Response
{
return new Response(200, ['content-type' => 'application/json'], '{"data":[]}');
}
}
$chat = new AccountClient('hchat_de_prueba', options: new ClientOptions(httpClient: new ClienteFalso()));
bash
php examples/06_extremo_a_extremo.php
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.