PHP code example of nargor / tiktok-live-connector-php

1. Go to this page and download the library: Download nargor/tiktok-live-connector-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/ */

    

nargor / tiktok-live-connector-php example snippets



React\EventLoop\Loop;
use TikTokLive\Event\WebcastEvent;
use TikTokLive\TikTokLiveConnection;

$loop = Loop::get();
$tiktokUsername = 'officialgeilegisela';

// Create a new wrapper object and pass the username
$connection = new TikTokLiveConnection($tiktokUsername, $loop);

// Connect to the chat
$connection->connect()->then(
    fn ($state) => printf("Connected to roomId %s\n", $state['roomId']),
    fn (\Throwable $e) => fwrite(STDERR, "Failed to connect: {$e->getMessage()}\n"),
);

// Listen for chat messages (comments)
$connection->on(WebcastEvent::CHAT, function (array $data): void {
    $user = $data['user']['uniqueId'] ?? '?';
    printf("%s writes: %s\n", $user, $data['comment']);
});

// And gifts sent to the streamer
$connection->on(WebcastEvent::GIFT, function (array $data): void {
    $user = $data['user']['uniqueId'] ?? '?';
    printf("%s sends giftId=%d x%d\n", $user, $data['giftId'], $data['repeatCount']);
});

// Drive the ReactPHP event loop (blocks until disconnect)
$loop->run();

$connection = new TikTokLiveConnection('username', $loop, [
    'signApiKey' => 'your-eulerstream-key',
    'sessionId' => 'paste-from-browser-cookie',
    'ttTargetIdc' => 'useast1a',
    'fetchRoomInfoOnConnect' => false,
]);

// or pass it explicitly
$connection = new TikTokLiveConnection('username', $loop, [
    'signApiKey' => 'paste_key_here',
]);

$connection->on(WebcastEvent::CONNECTED, function (array $state): void {
    printf("Connected to roomId %s\n", $state['roomId']);
});

$connection->on(WebcastEvent::DISCONNECTED, function (array $info): void {
    printf("Disconnected: code=%d reason=%s\n", $info['code'], $info['reason']);
});

$connection->on(WebcastEvent::ERROR, function (\Throwable $e): void {
    fwrite(STDERR, "Error: {$e->getMessage()}\n");
});

$connection->on(WebcastEvent::RAW_MESSAGE, function (string $type, string $bytes): void {
    printf("type=%s payload=%d bytes\n", $type, strlen($bytes));
    // base64-encode and report in an issue for new message-type support:
    // base64_encode($bytes)
});

$connection->on(WebcastEvent::CHAT, function (array $data): void {
    printf("%s -> %s\n", $data['user']['uniqueId'] ?? '?', $data['comment']);
});

$connection->on(WebcastEvent::GIFT, function (array $data): void {
    if ($data['repeatEnd'] === 0) {
        // Streak in progress — show temporarily
        printf("%s is sending giftId=%d x%d\n",
            $data['user']['uniqueId'] ?? '?',
            $data['giftId'],
            $data['repeatCount'],
        );
    } else {
        // Streak ended (or non-streakable gift) — process the final total
        printf("%s has sent giftId=%d x%d\n",
            $data['user']['uniqueId'] ?? '?',
            $data['giftId'],
            $data['repeatCount'],
        );
    }
});

$connection->on(WebcastEvent::LIKE, function (array $data): void {
    printf("%s sent %d likes (total %d)\n",
        $data['user']['uniqueId'] ?? '?',
        $data['likeCount'],
        $data['totalLikeCount'],
    );
});


React\EventLoop\Loop;
use TikTokLive\Event\WebcastEvent;
use TikTokLive\TikTokLiveConnection;

$loop = Loop::get();
$conn = new TikTokLiveConnection($argv[1] ?? 'officialgeilegisela', $loop);

$conn->on(WebcastEvent::CHAT, fn (array $m) =>
    printf("%s: %s\n", $m['user']['uniqueId'] ?? '?', $m['comment'])
);

$conn->connect();
$loop->run();

use React\EventLoop\Loop;
use TikTokLive\Event\WebcastEvent;
use TikTokLive\TikTokLiveConnection;

$loop = Loop::get();
$username = $argv[1];

$register = function () use (&$register, $loop, $username): void {
    $conn = new TikTokLiveConnection($username, $loop);

    $conn->on(WebcastEvent::CHAT, fn (array $m) =>
        printf("%s: %s\n", $m['user']['uniqueId'] ?? '?', $m['comment'])
    );

    $conn->on(WebcastEvent::DISCONNECTED, function () use ($loop, $register): void {
        echo "Disconnected — retrying in 10s\n";
        $loop->addTimer(10, $register);
    });

    $conn->connect()->then(
        null,
        function (\Throwable $e) use ($loop, $register): void {
            fwrite(STDERR, "Connect failed: {$e->getMessage()} — retry in 30s\n");
            $loop->addTimer(30, $register);
        },
    );
};

$register();
$loop->run();

$logFile = fopen('chat-' . date('Y-m-d') . '.log', 'a');

$conn->on(WebcastEvent::CHAT, function (array $m) use ($logFile): void {
    fwrite($logFile, sprintf(
        "[%s] %s: %s\n",
        date('H:i:s'),
        $m['user']['uniqueId'] ?? '?',
        $m['comment'],
    ));
});

use PDO;

$pdo = new PDO('mysql:host=localhost;dbname=tiktok;charset=utf8mb4',
    'user', 'pass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$insertChat = $pdo->prepare(
    'INSERT INTO chats (username, user_id, comment, created_at) VALUES (?, ?, ?, NOW())'
);
$insertGift = $pdo->prepare(
    'INSERT INTO gifts (username, user_id, gift_id, repeat_count, repeat_end, created_at)
     VALUES (?, ?, ?, ?, ?, NOW())'
);

$conn->on(WebcastEvent::CHAT, function (array $m) use ($insertChat): void {
    $insertChat->execute([
        $m['user']['uniqueId'] ?? null,
        $m['user']['userId'] ?? null,
        $m['comment'],
    ]);
});

$conn->on(WebcastEvent::GIFT, function (array $m) use ($insertGift): void {
    // Only persist when the streak ends, to avoid duplicate rows for combos
    if ($m['repeatEnd'] !== 1) {
        return;
    }
    $insertGift->execute([
        $m['user']['uniqueId'] ?? null,
        $m['user']['userId'] ?? null,
        $m['giftId'],
        $m['repeatCount'],
        $m['repeatEnd'],
    ]);
});

use GuzzleHttp\Client;

$http = new Client(['timeout' => 5]);
$webhookUrl = 'https://your-app.example.com/tiktok/event';

$forward = function (string $event, array $payload) use ($http, $webhookUrl): void {
    $http->postAsync($webhookUrl, [
        'json' => ['event' => $event, 'data' => $payload, 'ts' => time()],
    ])->then(null, fn () => null); // swallow errors so listener doesn't crash
};

$conn->on(WebcastEvent::CHAT, fn (array $m) => $forward('chat', $m));
$conn->on(WebcastEvent::GIFT, fn (array $m) => $forward('gift', $m));
$conn->on(WebcastEvent::LIKE, fn (array $m) => $forward('like', $m));

$totals = ['chat' => 0, 'gift' => 0, 'likes' => 0];

$render = function () use (&$totals): void {
    printf("\rchats: %d  gifts: %d  likes: %d   ",
        $totals['chat'], $totals['gift'], $totals['likes']);
};

$conn->on(WebcastEvent::CHAT, function () use (&$totals, $render): void {
    $totals['chat']++; $render();
});
$conn->on(WebcastEvent::GIFT, function (array $m) use (&$totals, $render): void {
    if ($m['repeatEnd'] === 1) { $totals['gift'] += $m['repeatCount']; $render(); }
});
$conn->on(WebcastEvent::LIKE, function (array $m) use (&$totals, $render): void {
    $totals['likes'] += $m['likeCount']; $render();
});

$conn = new TikTokLiveConnection('username', $loop, [
    'sessionId'   => '<account_session_id>',
    'ttTargetIdc' => 'useast1a', // varies by your region
]);
bash
php examples/chat-reader.php <username>
bash
# via env var (recommended)
SIGN_API_KEY=your_key php examples/chat-reader.php <username>
bash
SIGN_API_URL=https://my-sign-server.example.com php examples/chat-reader.php <user>