Skip to content

PHP Integration

Complete PHP examples for Lunar Stream API integration.

Requirements

  • PHP 8.0+
  • Composer
  • Guzzle HTTP Client

Installation

bash
composer require guzzlehttp/guzzle

API Client

php
<?php
// src/LunarStreamClient.php

namespace App\LunarStream;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class LunarStreamClient
{
    private Client $http;
    private string $baseUrl;
    private string $apiKey;
    private string $projectId;

    public function __construct(string $apiKey, string $projectId)
    {
        $this->apiKey = $apiKey;
        $this->projectId = $projectId;
        $this->baseUrl = getenv('LUNAR_STREAM_API_URL') ?: 'https://api.lunarstream.kozow.com/api/v1';

        $this->http = new Client([
            'base_uri' => $this->baseUrl,
            'headers' => [
                'ls-api-key' => $this->apiKey,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);
    }

    public function getMediaServers(): array
    {
        $response = $this->http->get('/media-servers/available', [
            'query' => ['projectId' => $this->projectId],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['data'] ?? [];
    }

    public function createLivestream(string $name, string $mediaServerId): array
    {
        $response = $this->http->post('/livestream', [
            'json' => [
                'name' => $name,
                'projectId' => $this->projectId,
                'mediaServerId' => $mediaServerId,
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['data'] ?? [];
    }

    public function getLivestream(string $id): array
    {
        $response = $this->http->get("/livestream/{$id}", [
            'query' => ['projectId' => $this->projectId],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['data'] ?? [];
    }

    public function listLivestreams(int $page = 1, int $limit = 10): array
    {
        $response = $this->http->get('/livestream', [
            'query' => [
                'projectId' => $this->projectId,
                'page' => $page,
                'limit' => $limit,
            ],
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    public function deleteLivestream(string $id): array
    {
        $response = $this->http->delete("/livestream/{$id}", [
            'query' => ['projectId' => $this->projectId],
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    public function generatePushToken(string $streamKey, int $expiresIn = 3600): array
    {
        $response = $this->http->post('/livestream/generate-push-token', [
            'json' => [
                'projectId' => $this->projectId,
                'streamKey' => $streamKey,
                'expiresIn' => $expiresIn,
            ],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['data'] ?? [];
    }

    public function getStreamInfo(string $streamKey): array
    {
        $client = new Client([
            'base_uri' => $this->baseUrl,
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);

        $response = $client->get("/livestreams/stream-info/{$streamKey}");

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['data'] ?? [];
    }
}

Laravel Controller Example

php
<?php
// app/Http/Controllers/StreamController.php

namespace App\Http\Controllers;

use App\LunarStream\LunarStreamClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Exception;

class StreamController extends Controller
{
    private LunarStreamClient $client;

    public function __construct()
    {
        $this->client = new LunarStreamClient(
            config('services.lunarstream.api_key'),
            config('services.lunarstream.project_id')
        );
    }

    public function create(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        try {
            $servers = $this->client->getMediaServers();

            if (empty($servers)) {
                return response()->json([
                    'error' => 'No media servers available'
                ], 503);
            }

            $stream = $this->client->createLivestream(
                $request->input('name'),
                $servers[0]['id']
            );

            return response()->json([
                'id' => $stream['id'],
                'name' => $stream['name'],
                'status' => $stream['status'],
                'rtmpUrl' => $stream['rmtpServer'] . '/' . $stream['streamKeyWithParams'],
                'hlsUrl' => $stream['hlsSources'][0]['url'] ?? null,
            ]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'Failed to create stream: ' . $e->getMessage()
            ], 500);
        }
    }

    public function show(string $streamKey): JsonResponse
    {
        try {
            $stream = $this->client->getStreamInfo($streamKey);

            return response()->json([
                'name' => $stream['name'],
                'status' => $stream['status'],
                'hlsSources' => $stream['hlsSources'] ?? [],
            ]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'Stream not found'
            ], 404);
        }
    }

    public function index(Request $request): JsonResponse
    {
        try {
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);

            $result = $this->client->listLivestreams($page, $limit);

            return response()->json([
                'streams' => $result['data'] ?? [],
                'pagination' => $result['meta']['pagination'] ?? null,
            ]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'Failed to list streams'
            ], 500);
        }
    }

    public function destroy(string $id): JsonResponse
    {
        try {
            $this->client->deleteLivestream($id);

            return response()->json(['success' => true]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'Failed to delete stream'
            ], 500);
        }
    }

    public function refreshToken(Request $request, string $streamKey): JsonResponse
    {
        try {
            $expiresIn = $request->input('expiresIn', 7200);
            $token = $this->client->generatePushToken($streamKey, $expiresIn);

            return response()->json([
                'rtmpUrl' => $token['rtmpUrl'],
                'streamKeyWithToken' => $token['streamKeyWithToken'],
                'expiresAt' => $token['expiresAt'],
            ]);

        } catch (Exception $e) {
            return response()->json([
                'error' => 'Failed to refresh token'
            ], 500);
        }
    }
}

Laravel Routes

php
<?php
// routes/api.php

use App\Http\Controllers\StreamController;
use Illuminate\Support\Facades\Route;

Route::prefix('streams')->group(function () {
    Route::post('/', [StreamController::class, 'create']);
    Route::get('/', [StreamController::class, 'index']);
    Route::get('/{streamKey}', [StreamController::class, 'show']);
    Route::delete('/{id}', [StreamController::class, 'destroy']);
    Route::post('/{streamKey}/refresh-token', [StreamController::class, 'refreshToken']);
});

Laravel Configuration

php
<?php
// config/services.php

return [
    // ... other services

    'lunarstream' => [
        'api_key' => env('LUNAR_STREAM_API_KEY'),
        'project_id' => env('LUNAR_STREAM_PROJECT_ID'),
        'api_url' => env('LUNAR_STREAM_API_URL', 'https://api.lunarstream.kozow.com/api/v1'),
    ],
];

Environment Variables

bash
# .env
LUNAR_STREAM_API_URL=https://api.lunarstream.kozow.com/api/v1
LUNAR_STREAM_API_KEY=ls_proj_v1_your_api_key_here
LUNAR_STREAM_PROJECT_ID=your-project-id-here

Plain PHP Example

php
<?php
// index.php

require_once 'vendor/autoload.php';
require_once 'src/LunarStreamClient.php';

use App\LunarStream\LunarStreamClient;

$client = new LunarStreamClient(
    getenv('LUNAR_STREAM_API_KEY'),
    getenv('LUNAR_STREAM_PROJECT_ID')
);

// Create a stream
$servers = $client->getMediaServers();
if (!empty($servers)) {
    $stream = $client->createLivestream('My Stream', $servers[0]['id']);
    
    echo "Stream created!\n";
    echo "RTMP URL: " . $stream['rmtpServer'] . '/' . $stream['streamKeyWithParams'] . "\n";
    echo "HLS URL: " . ($stream['hlsSources'][0]['url'] ?? 'N/A') . "\n";
}

// Get stream info
$streamInfo = $client->getStreamInfo('ee04affe2a669854052102fe762bd715');
echo "Stream status: " . $streamInfo['status'] . "\n";

Usage

bash
# Create a stream
curl -X POST http://localhost:8000/api/streams \
  -H "Content-Type: application/json" \
  -d '{"name": "My Stream"}'

# Get stream info
curl http://localhost:8000/api/streams/ee04affe2a669854052102fe762bd715

# List streams
curl "http://localhost:8000/api/streams?page=1&limit=10"

# Refresh token
curl -X POST http://localhost:8000/api/streams/ee04affe2a669854052102fe762bd715/refresh-token \
  -H "Content-Type: application/json" \
  -d '{"expiresIn": 7200}'

Released under the MIT License.