Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Sdk Laravel Package

getkeymanager/php-sdk

PHP SDK for integrating with GetKeyManager: manage API keys and access securely from your Laravel or PHP apps. Simple client setup, request helpers, and authentication support to streamline key creation, retrieval, rotation, and usage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require getkeymanager/php-sdk
    

    Ensure your PHP version (8.1+) matches the SDK's requirements.

  2. Initialize the Client

    use GetKeyManager\Client;
    
    $client = new Client(
        env('KEYMANAGER_API_KEY'),
        env('KEYMANAGER_API_SECRET'),
        env('KEYMANAGER_APP_ID')
    );
    
  3. First Use Case: Validate a License

    $licenseKey = 'YOUR_LICENSE_KEY_HERE';
    $result = $client->validateLicense($licenseKey);
    
    if ($result->isValid()) {
        // Proceed with authenticated logic
    } else {
        // Handle invalid license (e.g., show error)
    }
    
  4. Check Documentation

    • Review the official docs for API endpoints, response formats, and rate limits.
    • Focus on the Client class methods: validateLicense(), activateLicense(), deactivateLicense(), and getLicenseDetails().

Implementation Patterns

Core Workflows

  1. License Validation in Middleware Use Laravel middleware to enforce license checks before critical routes:

    namespace App\Http\Middleware;
    
    use GetKeyManager\Client;
    use Closure;
    
    class LicenseMiddleware
    {
        protected $client;
    
        public function __construct(Client $client)
        {
            $this->client = $client;
        }
    
        public function handle($request, Closure $next)
        {
            $licenseKey = $request->header('X-License-Key');
            $result = $this->client->validateLicense($licenseKey);
    
            if (!$result->isValid()) {
                abort(403, 'Invalid license');
            }
    
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'license' => \App\Http\Middleware\LicenseMiddleware::class,
    ];
    
  2. Activation on First Run Trigger license activation during application boot or a one-time setup:

    public function boot()
    {
        $licenseKey = config('app.license_key');
        $client = app(GetKeyManager\Client::class);
    
        if (!$client->isLicenseActivated($licenseKey)) {
            $client->activateLicense($licenseKey, [
                'hardware_id' => $this->getHardwareId(),
                'user_email'  => auth()->user()->email ?? null,
            ]);
        }
    }
    
  3. Graceful Degradation Cache license validation results (e.g., 5-minute TTL) to reduce API calls:

    $cacheKey = "license_{$licenseKey}";
    $result = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($licenseKey) {
        return $client->validateLicense($licenseKey);
    });
    

Integration Tips

  • Environment Variables Store KEYMANAGER_API_KEY, KEYMANAGER_API_SECRET, and KEYMANAGER_APP_ID in .env:

    KEYMANAGER_API_KEY=your_api_key_here
    KEYMANAGER_API_SECRET=your_secret_here
    KEYMANAGER_APP_ID=your_app_id_here
    
  • Dependency Injection Bind the Client in AppServiceProvider for seamless Laravel integration:

    public function register()
    {
        $this->app->singleton(GetKeyManager\Client::class, function ($app) {
            return new GetKeyManager\Client(
                env('KEYMANAGER_API_KEY'),
                env('KEYMANAGER_API_SECRET'),
                env('KEYMANAGER_APP_ID')
            );
        });
    }
    
  • Testing Use mocks for unit tests (e.g., with Laravel's Mockery):

    $mockClient = Mockery::mock(GetKeyManager\Client::class);
    $mockClient->shouldReceive('validateLicense')
               ->once()
               ->andReturn((new LicenseResult())->setValid(true));
    
    $this->app->instance(GetKeyManager\Client::class, $mockClient);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • The SDK enforces API rate limits (e.g., 60 requests/minute). Cache responses aggressively or implement exponential backoff for retries.
    • Debugging: Check HTTP status codes (e.g., 429 Too Many Requests) and X-RateLimit-Remaining headers.
  2. Hardware Binding

    • Licenses may bind to hardware fingerprints (e.g., MAC address, disk serial). Test activation on different machines to avoid false positives.
    • Fix: Use hardware_id parameter during activation to specify a consistent identifier (e.g., a UUID stored in your DB).
  3. Offline Mode

    • The SDK requires internet access for all API calls. For offline-first apps:
      • Cache license data locally (e.g., Redis) and sync when online.
      • Implement a fallback mode with reduced features (e.g., read-only).
  4. License Expiry

    • Validate expiry dates in your logic:
      $result = $client->validateLicense($licenseKey);
      if ($result->isValid() && $result->getExpiryDate() < now()) {
          // Handle expired license
      }
      
  5. API Key Rotation

    • Rotate KEYMANAGER_API_KEY/API_SECRET periodically. Update all environments and redeploy.
    • Tip: Use Laravel's config:cache to avoid downtime during key rotation.

Debugging

  • Enable Verbose Logging Set the DEBUG environment variable to log raw API responses:

    $client = new Client(..., ..., true); // Enable debug mode
    

    Logs appear in storage/logs/laravel.log.

  • Common Errors

    Error Cause Solution
    InvalidLicenseKeyException Malformed or revoked license key. Verify the key format and check KeyManager dashboard.
    AuthenticationFailedException Invalid API key/secret. Regenerate keys in KeyManager settings.
    NetworkTimeoutException API server unreachable. Check network connectivity or retry.
    RateLimitExceededException Too many requests. Implement caching or backoff.

Extension Points

  1. Custom License Metadata Extend the LicenseResult class to add app-specific data:

    class AppLicenseResult extends GetKeyManager\LicenseResult
    {
        public function getFeatureFlags(): array
        {
            return json_decode($this->metadata['feature_flags'] ?? '[]', true);
        }
    }
    
  2. Webhook Integration Listen for license events (e.g., expiry, revocation) via KeyManager webhooks:

    Route::post('/keymanager-webhook', function (Request $request) {
        $payload = $request->validate([
            'event' => 'required|string',
            'data'  => 'required|array',
        ]);
    
        // Handle event (e.g., invalidate cached license)
        Cache::forget("license_{$payload['data']['license_key']}");
    });
    
  3. Fallback for Air-Gapped Systems Generate offline-validatable licenses using the SDK’s generateOfflineToken() (if supported):

    $token = $client->generateOfflineToken($licenseKey, now()->addDays(7));
    // Store $token securely and validate locally later.
    
  4. Multi-Tenant Licensing Scope licenses to tenants by appending tenant IDs to keys:

    $tenantLicenseKey = "TENANT_{$tenantId}_{$licenseKey}";
    $result = $client->validateLicense($tenantLicenseKey);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin