PHP code example of uchara / uchara-php

1. Go to this page and download the library: Download uchara/uchara-php 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/ */

    

uchara / uchara-php example snippets




chara\SDK\ServerSDK;

$client = new ServerSDK(
    apiUrl: 'https://api.uchara.com',
    apiKey: getenv('UCHARA_API_KEY')
);

// Send a message
$message = $client->sendMessage('conv_abc123', [
    'content' => 'Your order has shipped!',
    'sender_type' => 'bot',
]);

echo "Message sent: {$message['id']}\n";

// List conversations
$conversations = $client->listConversations([
    'status' => 'open',
    'limit' => 10,
]);

foreach ($conversations as $conv) {
    echo "Conversation: {$conv['id']} - {$conv['contact_name']}\n";
}

// Canonical member methods
$members = $client->listMembers(['role' => 'agent']);
$member  = $client->getMember('member_123');
$created = $client->createMember(['email' => '[email protected]', 'role' => 'agent'], 'idem-key-1');
$client->updateMember('member_123', ['name' => 'Alice']);
$client->updateMemberRole('member_123', 'admin');
$client->deactivateMember('member_123');
$client->reactivateMember('member_123');
$client->deleteMember('member_123');

// Agent aliases — identical behaviour
$agents = $client->listAgents();
$agent  = $client->getAgent('member_123');
$client->createAgent(['email' => '[email protected]']);
$client->updateAgent('member_123', ['name' => 'Alice']);
$client->deactivateAgent('member_123');
$client->reactivateAgent('member_123');
$client->deleteAgent('member_123');

$invite = $client->inviteMember(['email' => '[email protected]', 'role' => 'agent']);
$invites = $client->listInvites();
$client->revokeInvite('invite_123');

$channels = $client->listChannels();
$channel  = $client->getChannel('channel_123'); // filters the list (no GET-by-id route)
$client->createChannel(['name' => 'WhatsApp', 'type' => 'whatsapp']);
$client->updateChannel('channel_123', ['name' => 'WA']);
$client->deleteChannel('channel_123');

$bots = $client->listBots();
$client->createBot(['name' => 'Support Bot']);
$client->updateBot('bot_123', ['name' => 'Support Bot v2']);
$client->deleteBot('bot_123');

// Message aliases
$client->sendMessageToConversation('conv_1', ['content' => 'hi']);
$messages = $client->listMessages('conv_1');
$messages = $client->getConversationMessages('conv_1');



chara\SDK\AgentSDK;

$agent = new AgentSDK('https://api.uchara.com');
$agent->login(
    email: getenv('UCHARA_AGENT_EMAIL'),
    password: getenv('UCHARA_AGENT_PASSWORD'),
    workspaceSlug: getenv('UCHARA_WORKSPACE_SLUG') ?: null,
);

$message = $agent->sendMessage('conv_abc123', [
    'content' => 'Halo, saya siap membantu.',
]);

$agent->refresh();

// Authorized assignee/admin invites an existing workspace member to collaborate.
$agent->inviteToConversation('conv_abc123', 'member_456');

// The invited agent (a separate authenticated AgentSDK session) accepts by joining.
// Join persists multi-agent membership and emits `conversation.joined`.
$agent->joinConversation('conv_abc123');

// The joined agent can now operate as a collaborator (send messages, add notes,
// resolve, etc.) on the conversation.
$agent->sendMessage('conv_abc123', ['content' => 'Saya ikut menangani.']);

// A collaborator removes their membership when done.
$agent->leaveConversation('conv_abc123');

// Bot-to-agent takeover (distinct from collaborator approval).
$agent->takeoverConversation('conv_abc123');

// Backend only — UCHARA_API_KEY must remain server-side.
$server = new ServerSDK('https://api.uchara.com', getenv('UCHARA_API_KEY'));
$session = $server->createAgentSession('[email protected]');

// Return $session to your dashboard frontend over your own authenticated HTTPS endpoint.



chara\SDK\ServerSDK;

// Backend only — UCHARA_API_KEY must remain server-side.
$server = new ServerSDK('https://api.uchara.com', getenv('UCHARA_API_KEY'));

// Issue a one-time ticket for the target member (optional channel scope).
$result = $server->http()->post('/v1/auth/sso/ticket', [
    'email' => '[email protected]',
    // 'channel_ids' => ['<channel-uuid>'], // optional; omitted = full workspace
]);

// Return $result['redirect_url'] from your own authenticated HTTPS endpoint.
// The browser opens it; the dashboard bootstrap exchanges the ticket and
// strips it from the URL.
$redirectUrl = $result['redirect_url'];



chara\SDK\VisitorSDK;

$visitor = new VisitorSDK(
    apiUrl: 'https://api.uchara.com',
    widgetToken: 'widget_token_123'
);

// Create a visitor session (stores the visitor JWT for subsequent calls)
$session = $visitor->init(['name' => 'Alice', 'email' => '[email protected]']);

$config = $visitor->getConfig();

$active = $visitor->getActiveConversation(); // null when none exists
if ($active === null) {
    $active = $visitor->startConversation(['message' => 'Hello']);
}

$visitor->sendMessage($active['id'], ['content' => 'Hi there']);
$messages = $visitor->getMessages($active['id'], ['limit' => 20]);
$visitor->close($active['id']);

use Uchara\SDK\DeliveryStatus;

if ($message['delivery_status'] === DeliveryStatus::READ) {
    // the recipient has read the message
}

// Visitor marks the responder's messages as read (widget)
$visitor->markConversationRead($conversationId); // ['updated' => int]

// Agent marks the visitor's messages as read (dashboard)
$agent->markConversationRead($conversationId);   // ['marked_read' => int]

use Uchara\SDK\Uchara;

$server = Uchara::server('https://api.uchara.com', 'uchara_sk_...');
$agent = Uchara::agent('https://api.uchara.com');
$visitor = Uchara::visitor('https://api.uchara.com', 'widget_token_...');

// From a config array
$sdk = Uchara::make([
    'api_url' => 'https://api.uchara.com',
     'api_key' => 'uchara_sk_...',
     'access_token' => 'agent_access_token',
     'default' => 'server', // or 'agent' or 'visitor'

]);

// .env
UCHARA_API_URL=https://api.uchara.com
UCHARA_API_KEY=uchara_sk_...
UCHARA_ACCESS_TOKEN=agent_access_token
UCHARA_DEFAULT=server

use Uchara\SDK\Laravel\Facades\Uchara;

$members = Uchara::listMembers();          // forwards to the default SDK
$server  = Uchara::server();               // explicit ServerSDK
$agent   = Uchara::agent();                // explicit AgentSDK
$visitor = Uchara::visitor();              // explicit VisitorSDK

use Uchara\SDK\UcharaException;

try {
    $message = $client->sendMessage('conv_id', ['content' => 'Hello!']);
} catch (UcharaException $e) {
    echo "Error ({$e->getStatus()}): {$e->getMessage()}\n";
    if ($e->getDetails()) {
        print_r($e->getDetails());
    }
}

$response = $client->http()->request('GET', '/v1/workspace/members', ['query' => ['limit' => 10]]);
$status = $response->status();
$meta   = $response->meta();
$data   = $response->data();
bash
composer 
bash
php artisan vendor:publish --tag=uchara-config