1. Go to this page and download the library: Download omnicast/laravel-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/ */
omnicast / laravel-sdk example snippets
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Omnicast\LaravelSdk\Facades\Omnicast;
use Omnicast\LaravelSdk\Constants\Role;
use Omnicast\LaravelSdk\Exceptions\OmnicastException;
class StreamController extends Controller
{
/**
* 1. Host starts a live stream
* POST /api/stream/start
*/
public function startLive(Request $request): JsonResponse
{
$user = $request->user();
$roomId = 'room_' . uniqid();
try {
// Step 1: Create room on media server
$room = Omnicast::createRoom(
roomId: $roomId,
hostId: (string) $user->id,
roomName: $request->input('title', "{$user->name}'s Live"),
roomType: 'live'
);
// Step 2: Generate token with host permissions and ICE servers
$authData = Omnicast::generateToken(
userId: (string) $user->id,
userName: $user->name,
avatarUrl: $user->avatar_url ?? '',
role: Role::HOST,
roomId: $roomId,
canPublish: true,
canSubscribe: true
);
// Step 3: Generate WebSocket signaling URL
$wsUrl = Omnicast::getWebSocketUrl($authData['token']);
return response()->json([
'success' => true,
'room_id' => $roomId,
'token' => $authData['token'],
'ice_servers' => $authData['ice_servers'],
'ws_url' => $wsUrl,
]);
} catch (OmnicastException $e) {
if ($e->isDraining()) {
return response()->json(['error' => 'Server is currently undergoing maintenance.'], 503);
}
return response()->json(['error' => $e->getMessage()], 500);
}
}
/**
* 2. Viewer joins a live stream
* POST /api/stream/join
*/
public function joinLive(Request $request): JsonResponse
{
$user = $request->user();
$roomId = $request->input('room_id');
try {
// Generate viewer token (canPublish: false)
$authData = Omnicast::generateToken(
userId: (string) $user->id,
userName: $user->name,
avatarUrl: $user->avatar_url ?? '',
role: Role::VIEWER,
roomId: $roomId,
canPublish: false,
canSubscribe: true
);
$wsUrl = Omnicast::getWebSocketUrl($authData['token']);
return response()->json([
'success' => true,
'token' => $authData['token'],
'ice_servers' => $authData['ice_servers'],
'ws_url' => $wsUrl,
]);
} catch (OmnicastException $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
}
/**
* 3. Send a virtual gift to the host
* POST /api/stream/gift
*/
public function sendGift(Request $request): JsonResponse
{
$sender = $request->user();
$roomId = $request->input('room_id');
$receiverId = $request->input('host_id');
$coins = (int) $request->input('coins', 50);
// Deduct coins from user balance in your database here...
// Broadcast gift into the live room in real time
$res = Omnicast::sendGift(
roomId: $roomId,
senderId: (string) $sender->id,
senderName: $sender->name,
giftId: $request->input('gift_id', 'rose_01'),
giftName: $request->input('gift_name', 'Rose'),
receiverId: $receiverId,
coins: $coins,
points: $coins,
amount: 1
);
return response()->json($res);
}
/**
* 4. End room (Admin or Host)
* POST /api/stream/end
*/
public function endLive(Request $request): JsonResponse
{
$roomId = $request->input('room_id');
// Forcefully terminates room and disconnects all participants
$res = Omnicast::forceEndRoom($roomId);
return response()->json($res);
}
}
use App\Http\Controllers\OmnicastWebhookController;
Route::post('/omnicast/webhook', [OmnicastWebhookController::class, 'handle']);
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Omnicast\LaravelSdk\Facades\Omnicast;
use Omnicast\LaravelSdk\Constants\WebhookType;
use Omnicast\LaravelSdk\Exceptions\OmnicastException;
class OmnicastWebhookController extends Controller
{
public function handle(Request $request): JsonResponse
{
$payload = $request->getContent();
$signature = (string) $request->header('X-Signature');
try {
// Verifies X-Signature header and decodes into WebhookEvent DTO
$event = Omnicast::handleWebhook($payload, $signature);
match ($event->eventType) {
WebhookType::ROOM_STARTED => $this->onRoomStarted($event->roomId, $event->userId),
WebhookType::ROOM_ENDED => $this->onRoomEnded($event->roomId),
WebhookType::PARTICIPANT_JOINED => $this->onUserJoined($event->roomId, $event->userId),
WebhookType::PARTICIPANT_LEFT => $this->onUserLeft($event->roomId, $event->userId),
WebhookType::GIFT_SENT => $this->onGiftSent($event->data),
default => null,
};
return response()->json(['status' => 'acknowledged']);
} catch (OmnicastException $e) {
// Returns 403 if signature is invalid or tampered
return response()->json(['error' => $e->getMessage()], 403);
}
}
private function onRoomStarted(string $roomId, string $hostId): void
{
// Update database: Stream status = 'live'
}
private function onRoomEnded(string $roomId): void
{
// Update database: Stream status = 'ended'
}
private function onUserJoined(string $roomId, string $userId): void
{
// Increment viewer counter in cache/database
}
private function onUserLeft(string $roomId, string $userId): void
{
// Decrement viewer counter
}
private function onGiftSent(array $data): void
{
// Log transaction history
}
}
// Create a live room
$room = Omnicast::createRoom(
roomId: 'room_live_abc123',
hostId: 'user_101',
roomName: "Meharab's Live Show",
roomType: 'live' // 'live', 'pk', 'event'
);
// List all active rooms
$rooms = Omnicast::listRooms(); // or Omnicast::getRooms();
// Get single room details
$room = Omnicast::getRoom('room_live_abc123');
// Get total count of active rooms
$count = Omnicast::getRoomCount();
// Get viewers / participant list
$participants = Omnicast::getParticipants('room_live_abc123');
// Get participant count
$viewerCount = Omnicast::getParticipantCount('room_live_abc123');
// Calculate uptime in seconds from created_at
$seconds = Omnicast::getRoomUptime($room['created_at']);
// Fetch ICE server config from media server
$ice = Omnicast::getIceServers(userId: 'user_101');
// Fetch TURN server credentials from media server
$turn = Omnicast::getTurnCredentials(userId: 'user_101');
// Generate RFC 5766 TURN REST API credentials locally (zero network overhead)
$creds = Omnicast::generateTurnCredentials(userId: 'user_101', ttl: 86400);
// Returns: ['uris' => [...], 'username' => '...', 'password' => '...', 'ttl' => 86400]
// Overview of all active rooms with uptime_seconds and statistics
$overview = Omnicast::adminListRooms();
// Forcefully terminate and destroy an active room
$result = Omnicast::forceEndRoom('room_live_abc123'); // or Omnicast::closeRoom(...)
// Raw health response: GET /health
$health = Omnicast::healthCheck();
// Check if server is operational
if (Omnicast::isHealthy()) {
// Normal operation
}
// Check if server is draining connections for maintenance/restart
if (Omnicast::isDraining()) {
// Don't schedule new streams on this node
}
use Omnicast\LaravelSdk\Constants\WsAction;
use Omnicast\LaravelSdk\Constants\WsEvent;
// Get WebSocket connection URL with token
$wsUrl = Omnicast::getWebSocketUrl($token);
// => ws://127.0.0.1:8080/ws?token=eyJhbGci...
// Build standard message envelope
$message = Omnicast::formatWebSocketMessage(
action: WsAction::CHAT,
roomId: 'room_123',
userId: 'user_101',
payload: ['message' => 'Hello World!'],
extra: ['user_name' => 'Meharab']
);