PHP code example of masterix21 / laravel-licensing-filament-manager

1. Go to this page and download the library: Download masterix21/laravel-licensing-filament-manager 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/ */

    

masterix21 / laravel-licensing-filament-manager example snippets


use LucaLongo\LaravelLicensingFilamentManager\LaravelLicensingFilamentManagerPlugin;

public function panel(Panel $panel): Panel
{
    return $panel
        // ... other panel configuration
        ->plugins([
            LaravelLicensingFilamentManagerPlugin::make()
                ->navigationGroup('License Management') // Optional: customize navigation group
                ->navigationSort(10) // Optional: set navigation position
                ->enableStatistics(true) // Optional: enable/disable statistics dashboard
                ->enableBulkActions(true) // Optional: enable/disable bulk actions
        ]);
}

// config/licensing-filament-manager.php

return [
    'licensed_entities' => [
        // Map your model classes to their configuration
        \App\Models\User::class => [
            'title' => 'name', // The field to display as the entity's title
            'search' => ['name', 'email'], // Fields to search when selecting entities
        ],
        \App\Models\Team::class => [
            'title' => 'name',
            'search' => ['name', 'slug'],
        ],
        \App\Models\Organization::class => [
            'title' => 'company_name',
            'search' => ['company_name', 'tax_id'],
        ],
        // Add more models as needed
    ],
];

use Masterix21\LaravelLicensing\Models\LicenseScope;

$scope = LicenseScope::create([
    'name' => 'Enterprise',
    'slug' => 'enterprise',
    'identifier' => 'com.yourcompany.enterprise',
    'description' => 'Enterprise license with advanced features',
    'is_active' => true,
    'default_max_usages' => 10,
    'default_duration_days' => 365,
    'default_grace_days' => 30,
    'key_rotation_days' => 90, // Rotate keys every 90 days
    'meta' => [
        'features' => ['api_access', 'priority_support', 'white_label'],
        'rate_limits' => ['api_calls' => 10000],
    ],
]);

use Masterix21\LaravelLicensing\Models\LicenseTemplate;

$template = LicenseTemplate::create([
    'license_scope_id' => $scope->id,
    'name' => 'Enterprise Annual',
    'slug' => 'enterprise-annual',
    'tier_level' => 3,
    'is_active' => true,
    'license_duration_days' => 365,
    'supports_trial' => true,
    'trial_duration_days' => 30,
    'has_grace_period' => true,
    'grace_period_days' => 15,
    'base_configuration' => [
        'max_usages' => 10,
    ],
    'features' => [
        'api_access' => true,
        'white_label' => true,
        'custom_branding' => true,
    ],
    'entitlements' => [
        'api_calls_per_month' => 100000,
        'storage_gb' => 500,
        'team_members' => 50,
    ],
]);

use Masterix21\LaravelLicensing\Models\License;

// Create license with automatic key generation
$license = License::createWithKey([
    'license_scope_id' => $scope->id,
    'template_id' => $template->id,
    'licensable_type' => \App\Models\Organization::class,
    'licensable_id' => $organization->id,
    'max_usages' => 10,
    'expires_at' => now()->addYear(),
    'meta' => [
        'customer_name' => $organization->name,
        'invoice_number' => 'INV-2024-001',
    ],
]);

// The license key is temporarily available via:
$licenseKey = $license->temporaryLicenseKey;

use Masterix21\LaravelLicensing\Models\LicenseUsage;

// Record a new usage
$usage = LicenseUsage::create([
    'license_id' => $license->id,
    'usage_fingerprint' => hash('sha256', $deviceId . $machineId),
    'client_type' => 'desktop',
    'name' => 'John\'s MacBook Pro',
    'ip' => $request->ip(),
    'user_agent' => $request->userAgent(),
    'registered_at' => now(),
    'last_seen_at' => now(),
]);

// Update heartbeat
$usage->update(['last_seen_at' => now()]);

// Check if usage is active (seen in last 7 days)
$isActive = $usage->last_seen_at->diffInDays(now()) < 7;

use LucaLongo\LaravelLicensingFilamentManager\Resources\LicenseResource;

class CustomLicenseResource extends LicenseResource
{
    public static function beforeSave($record)
    {
        // Custom validation logic
        if ($record->scope->name === 'Enterprise' && !$record->user->is_verified) {
            throw new \Exception('Enterprise licenses 

namespace App\Filament\Resources;

use LucaLongo\LaravelLicensingFilamentManager\Resources\LicenseResource as BaseResource;

class LicenseResource extends BaseResource
{
    public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                ...parent::getFormSchema(),
                // Add your custom fields
                Forms\Components\TextInput::make('custom_field'),
            ]);
    }
}

use LucaLongo\LaravelLicensingFilamentManager\Widgets\LicenseStatsWidget;

class CustomRevenueWidget extends LicenseStatsWidget
{
    protected function getStats(): array
    {
        return [
            'total_revenue' => License::sum('price'),
            'monthly_revenue' => License::whereMonth('created_at', now()->month)->sum('price'),
        ];
    }
}

// License validation endpoint
Route::post('/api/license/validate', function (Request $request) {
    $license = License::where('key_hash', hash('sha256', $request->key))->firstOrFail();

    // Check if license is valid and active
    if ($license->status !== LicenseStatus::Active) {
        return response()->json(['valid' => false, 'reason' => 'License is not active']);
    }

    if ($license->isExpired()) {
        return response()->json(['valid' => false, 'reason' => 'License has expired']);
    }

    // Check usage limits
    $currentUsages = $license->usages()->where('revoked_at', null)->count();
    if ($currentUsages >= $license->max_usages) {
        return response()->json(['valid' => false, 'reason' => 'Maximum usage limit reached']);
    }

    // Create or update usage
    $fingerprint = hash('sha256', $request->device_id . $request->machine_id);
    $usage = $license->usages()->updateOrCreate(
        ['usage_fingerprint' => $fingerprint],
        [
            'client_type' => $request->client_type ?? 'unknown',
            'name' => $request->device_name,
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'last_seen_at' => now(),
        ]
    );

    return response()->json([
        'valid' => true,
        'usage_id' => $usage->id,
        'features' => $license->template?->features ?? [],
        'entitlements' => $license->template?->entitlements ?? [],
        'expires_at' => $license->expires_at,
    ]);
});

// Heartbeat endpoint to keep usage active
Route::post('/api/license/heartbeat', function (Request $request) {
    $usage = LicenseUsage::where('id', $request->usage_id)
        ->where('usage_fingerprint', $request->fingerprint)
        ->firstOrFail();

    $usage->update(['last_seen_at' => now()]);

    return response()->json(['success' => true]);
});
bash
php artisan vendor:publish --tag="laravel-licensing-filament-manager-config"
bash
php artisan vendor:publish --tag="laravel-licensing-filament-manager-migrations"
bash
php artisan migrate
bash
php artisan vendor:publish --tag="laravel-licensing-filament-manager-translations"