PHP code example of vntrungld / zalo-bot-php-sdk

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

    

vntrungld / zalo-bot-php-sdk example snippets


use ZaloBot\Client;

$bot = new Client('123456789:your-bot-token');

$me = $bot->getMe();
echo $me->accountName; // "bot.VDKyGxQvc"

$sent = $bot->sendMessage('chat_id_here', 'Xin chào 👋');
echo $sent->messageId;

use ZaloBot\Enum\ParseMode;
use ZaloBot\Enum\ChatAction;
use ZaloBot\Model\TextStyle;

// Plain text
$bot->sendMessage($chatId, 'Hello!');

// Markdown / HTML
$bot->sendMessage($chatId, '**bold**', ParseMode::Markdown);

// Inline styles: bold + colour over the first 7 characters
$bot->sendMessage($chatId, 'Xin chào bạn', null, [
    new TextStyle(start: 0, len: 7, styles: ['b', 'c_db342e']),
]);

// Photo with a caption
$bot->sendPhoto($chatId, 'https://example.com/image.jpg', 'A caption');

// Sticker (IDs from https://stickers.zaloapp.com/)
$bot->sendSticker($chatId, 'sticker_id');

// Voice — 1-on-1 only, must be a public .aac URL
$bot->sendVoice($userId, 'https://example.com/audio.aac');

// Typing indicator
$bot->sendChatAction($chatId, ChatAction::Typing);

foreach ($bot->getUpdates(timeout: 30) as $update) {
    if ($update->message->text !== null) {
        $bot->sendMessage($update->message->chat->id, 'You said: ' . $update->message->text);
    }
}

$bot->setWebhook('https://your-app.com/webhook', 'your-8-to-256-char-secret');

use ZaloBot\Webhook\WebhookHandler;
use ZaloBot\Enum\EventName;
use ZaloBot\Exception\WebhookException;

$handler = new WebhookHandler('your-8-to-256-char-secret');

try {
    $update = $handler->handle(
        file_get_contents('php://input'),
        $_SERVER['HTTP_X_BOT_API_SECRET_TOKEN'] ?? null,
    );
} catch (WebhookException $e) {
    http_response_code(403);
    exit;
}

if ($update->event() === EventName::TextReceived) {
    // ... react to $update->message
}

// Acknowledge the delivery
header('Content-Type: application/json');
echo json_encode(['ok' => true]);

use ZaloBot\Exception\ApiException;

try {
    $bot->sendMessage($chatId, 'hi');
} catch (ApiException $e) {
    // e.g. 401 invalid token, 429 quota exceeded
    error_log("Zalo API error {$e->getErrorCode()}: {$e->getMessage()}");
}

use GuzzleHttp\Client as GuzzleClient;

$bot = new Client(
    token: '123:abc',
    http: new GuzzleClient(['timeout' => 10]),
);