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.
Installation
composer require getkeymanager/php-sdk
Ensure your PHP version (8.1+) matches the SDK's requirements.
Initialize the Client
use GetKeyManager\Client;
$client = new Client(
env('KEYMANAGER_API_KEY'),
env('KEYMANAGER_API_SECRET'),
env('KEYMANAGER_APP_ID')
);
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)
}
Check Documentation
Client class methods: validateLicense(), activateLicense(), deactivateLicense(), and getLicenseDetails().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,
];
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,
]);
}
}
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);
});
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);
Rate Limiting
429 Too Many Requests) and X-RateLimit-Remaining headers.Hardware Binding
hardware_id parameter during activation to specify a consistent identifier (e.g., a UUID stored in your DB).Offline Mode
License Expiry
$result = $client->validateLicense($licenseKey);
if ($result->isValid() && $result->getExpiryDate() < now()) {
// Handle expired license
}
API Key Rotation
KEYMANAGER_API_KEY/API_SECRET periodically. Update all environments and redeploy.config:cache to avoid downtime during key rotation.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. |
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);
}
}
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']}");
});
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.
Multi-Tenant Licensing Scope licenses to tenants by appending tenant IDs to keys:
$tenantLicenseKey = "TENANT_{$tenantId}_{$licenseKey}";
$result = $client->validateLicense($tenantLicenseKey);
How can I help you explore Laravel packages today?