PHP code example of field-vn / zalo

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

    

field-vn / zalo example snippets


// AppServiceProvider::boot()
Zalo::auth(fn ($request) => $request->user()?->is_admin === true);

use FieldVn\Zalo\Laravel\Facades\Zalo;

Zalo::oa('cskh')->messages()->text($userId, 'Đơn hàng đã được xác nhận');
Zalo::bot('support')->text($chatId, 'Xin chào');

use FieldVn\Zalo\Core\Exceptions\ApiException;
use FieldVn\Zalo\Core\Exceptions\ZaloException;

try {
    Zalo::oa('cskh')->messages()->text($userId, 'Xin chào');
} catch (ApiException $e) {
    $e->errorCode;     // -230
    $e->getMessage();  // nguyên văn Zalo
    $e->info()->hint;  // việc cần làm (tiếng Việt)
    $e->toArray();     // payload JSON ổn định cho client
} catch (ZaloException $e) {
    return response()->json($e->toArray(), $e->httpStatus());
}

use FieldVn\Zalo\Core\Channels\OA\ZaloOutboundMessage;
use FieldVn\Zalo\Core\Channels\OA\ZaloRecipient;
use FieldVn\Zalo\Laravel\Facades\Zalo;

$result = Zalo::oa('cskh')->notifier()->send(
    new ZaloRecipient(zaloUserId: $userId, phone: $phone),
    new ZaloOutboundMessage(
        text: 'Đơn hàng đã được xác nhận',
        templateId: $templateId,
        templateData: ['order_code' => 'DH-123'],
    ),
);

zalo_oa('cskh')->messages()->text($userId, 'Xin chào');
zalo_bot('support')->text($chatId, 'Xin chào');

use FieldVn\Zalo\Core\Channels\OA\Messages\Button;
use FieldVn\Zalo\Core\Channels\OA\Messages\TextMessage;

Zalo::oa('cskh')->messages()->send(
    TextMessage::to($userId)
        ->text('Đơn hàng #1234 đang giao')
        ->button(Button::url('Theo dõi', 'https://shop.vn/don/1234'))
        ->button(Button::phone('Gọi shipper', '0900000000'))
);

$id = Zalo::oa('cskh')->uploads()->image('/duong/dan/anh.jpg');

Zalo::oa('cskh')->messages()->image($userId, $id, 'Ảnh sản phẩm');

use FieldVn\Zalo\Core\Channels\OA\Messages\RawMessage;

Zalo::oa('cskh')->messages()->send(
    RawMessage::to($userId)->message([
        'attachment' => [
            'type' => 'template',
            'payload' => ['template_type' => 'list', 'elements' => [/* … */]],
        ],
    ])
);

Zalo::oa('cskh')->request()->get('/v3.0/oa/duong-dan-moi', ['param' => 'x']);

$bot = Zalo::bot('support');

$bot->text($chatId, 'Xin chào');
$bot->photo($chatId, 'https://…/anh.png', 'Chú thích');
$bot->sticker($chatId, $stickerId);
$bot->typing($chatId);

$zbs = Zalo::oa('cskh')->zbs();

$zbs->templates();                          // mọi mẫu và trạng thái
$zbs->templates(filterPreset: 1);          // chỉ mẫu do App này tạo
$zbs->info($id);                            // GET /template/info/v2
$zbs->template($id);                        // info(), null khi id không tồn tại
$zbs->quota();                              // hạn mức còn lại hôm nay

$mediaId = $zbs->uploadImage('/path/logo.png'); // media_id, JPG/PNG, ≤ 500 KB

$zbs->create([
    'template_name' => 'Xác nhận đơn hàng ABC',
    'template_type' => 1,                   // 1 tuỳ chỉnh … 5 đánh giá
    'tag' => 1,                             // 1 Transaction, 2 CSKH, 3 Promotion
    'layout' => [/* header / body / footer đúng docs Zalo */],
    'params' => [['name' => 'order_code', 'type' => '11', 'sample_value' => 'DH-1']],
    'tracking_id' => 'tpl-dh-001',
]);

$zbs->edit($id, [/* cùng shape; chỉ sửa được mẫu REJECT */]);

$zbs->send('0987654321', $id, [
    'customer_name' => 'Nguyễn Văn A',
    'time'          => '18:00 20-08-2026',
]);

$zbs->status($msgId);
$zbs->waitForDelivery($msgId, timeoutSeconds: 60);          // poll giao tin
$zbs->waitUntilStatus($id, statuses: ['ENABLE', 'REJECT']); // poll duyệt mẫu

use FieldVn\Zalo\Core\Channels\OA\Capabilities\OaCapability;

$report = Zalo::oa('cskh')->capabilities()->check(
    OaCapability::zbsSend(templateId: $id),
);

if (! $report->available(OaCapability::ZbsSend)) {
    // hết quota ngày, mẫu chưa ENABLE, hoặc chưa liên kết ZBS
}

Zalo::oa();                  // OA active đầu tiên
Zalo::oa('marketing');       // theo slug
Zalo::availableOas();        // Collection<ZaloOa>, dùng cho dropdown

Zalo::oas(fn ($oa) => in_array('cskh', $oa->tags ?? []))
    ->each(fn ($channel) => $channel->messages()->text($userId, $noiDung));

use FieldVn\Zalo\Core\Channels\OA\Capabilities\CapabilityRegistry;
use FieldVn\Zalo\Core\Channels\OA\Capabilities\CapabilityResult;
use FieldVn\Zalo\Core\Channels\OA\Capabilities\OaCapability;

$report = Zalo::oa('cskh')->capabilities()->check(
    OaCapability::CsOutside48h,
    OaCapability::OpenApi,
    OaCapability::Zbs,
    OaCapability::ZbsQuota,
    OaCapability::ZbsTemplates,
    OaCapability::zbsTemplate(id: '433555'),
    OaCapability::zbsSend(templateId: '433555'),
);

$report->available(OaCapability::Zbs);
$report->get(OaCapability::ZbsQuota)->remain;
$report->toArray();

Zalo::oa('cskh')->capabilities()->check('open_api', 'zbs', 'zbs_quota');
Zalo::oa('cskh')->capabilities()->check(); // built-in; template/send cần id thì skip + hint

CapabilityRegistry::extend('my_key', function ($snapshot, $options) {
    return new CapabilityResult(
        key: 'my_key',
        available: true,
        value: $snapshot->packageName(),
    );
});

use FieldVn\Zalo\Laravel\Events\ZaloMessageReceived;

class TraLoiOa
{
    public function handle(ZaloMessageReceived $e): void
    {
        if ($e->text === null || $e->oa === null) {
            return;
        }

        zalo_oa($e->oa->slug)->messages()->text($e->userId, "Bạn vừa nói: {$e->text}");
    }
}

use FieldVn\Zalo\Laravel\Events\ZaloBotMessageReceived;

class TraLoiBot
{
    public function handle(ZaloBotMessageReceived $e): void
    {
        zalo_bot($e->bot->slug)->text($e->chatId, "Đã nhận: {$e->text}");
    }
}

use FieldVn\Zalo\Laravel\Facades\Zalo;

it('gửi xác nhận khi đặt hàng', function () {
    Zalo::fake();

    $this->post('/don-hang', ['san_pham' => 1]);

    Zalo::assertSentTo('user-1', 'Đơn hàng đã được xác nhận');
});

Zalo::fake()->push(['error' => -216, 'message' => 'Token hết hạn']);

// Đổi tầng HTTP
$this->app->bind(FieldVn\Zalo\Contracts\Transport::class, MyTransport::class);

// Đổi nguồn danh sách OA (multi-tenant, config thuần, API nội bộ…)
$this->app->bind(FieldVn\Zalo\Contracts\OaRepository::class, TenantOaRepository::class);
bash
php artisan zalo:install