PHP code example of hoangkhacphuc / zalo_bot

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

    

hoangkhacphuc / zalo_bot example snippets



Hoangkhacphuc\ZaloBot\Support\ZaloBotFactory;

$bot = ZaloBotFactory::create('<zalo-bot-access-token>');
$me = $bot->getMe();
echo $me->name;


Hoangkhacphuc\ZaloBot\BotConfig;
use Hoangkhacphuc\ZaloBot\Contracts\Repository;
use Hoangkhacphuc\ZaloBot\DTO\Message;
use Hoangkhacphuc\ZaloBot\Handler\TextMessage;
use Hoangkhacphuc\ZaloBot\Service\WebhookServiceFactory;
use Hoangkhacphuc\ZaloBot\Service\MessageDispatcher;

$payloads = json_decode(file_get_contents('php://input'), true);
$headers = getallheaders();

class MessageRepository implements Repository
{
    public function save(Message $message): void
    {
        // Save message to database or log
    }
}

class TextMessageHandler extends TextMessage
{
    public function handle(Message $message): void
    {
        file_put_contents('php://stderr', 'Text: '.$message->content.PHP_EOL);
    }
}

$botConfig = new BotConfig(
    '<zalo-access-token>',
    '<webhook-url>',
    '<webhook-secret>'
);

$dispatcher = new MessageDispatcher;
$dispatcher->registerHandler(new TextMessageHandler);

$webhookService = WebhookServiceFactory::create(
    $botConfig,
    new MessageRepository,
    dispatcher: $dispatcher,
);

// Handle
$webhookService->handle($payloads, $headers);

use Hoangkhacphuc\ZaloBot\Service\WebhookService;

Route::post('/zalo/webhook', function (Request $request, WebhookService $service) {
    $service->handle($request->all(), $request->headers->all());
    return response()->json(['ok' => true]);
});
bash
php artisan vendor:publish --tag=zalobot-config