SDK Reference
Complete SDK documentation for all supported languages.
Installationβ
Pythonβ
pip install quantumlock-sdk
Node.jsβ
npm install quantumlock-sdk
Javaβ
Add to pom.xml:
<dependency>
<groupId>com.softquantus</groupId>
<artifactId>quantumlock-sdk</artifactId>
<version>1.0.0</version>
</dependency>
C#β
dotnet add package QuantumLock.SDK
Python SDKβ
Basic Usageβ
from quantumlock_sdk import LicenseValidator
# Initialize validator (no API key needed for validation)
validator = LicenseValidator()
# Validate a license
result = validator.validate("QCOS-ABCD-EFGH-IJKL-MNOP")
if result["valid"]:
print("β
License is valid")
print(f"Features: {result['features']}")
print(f"Expires: {result['expires_at']}")
else:
print("β License is invalid")
Advanced Usageβ
from quantumlock_sdk import LicenseValidator, ValidationError
class MyApp:
def __init__(self):
self.validator = LicenseValidator(
cache_ttl=300, # Cache results for 5 minutes
offline_mode=False # Enable online validation
)
def check_license(self, license_key: str):
try:
result = self.validator.validate(license_key)
if not result["valid"]:
raise Exception("Invalid license")
# Check specific features
if "premium" not in result["features"]:
raise Exception("Premium feature not enabled")
# Check expiration
if result["days_remaining"] < 30:
print(f"β οΈ License expires in {result['days_remaining']} days")
return result
except ValidationError as e:
print(f"Validation error: {e}")
return None
Framework Integrationβ
FastAPIβ
from fastapi import FastAPI, HTTPException, Depends
from quantumlock_sdk import LicenseValidator
app = FastAPI()
validator = LicenseValidator()
def verify_license(license_key: str):
result = validator.validate(license_key)
if not result["valid"]:
raise HTTPException(status_code=401, detail="Invalid license")
return result
@app.get("/protected")
def protected_route(license: dict = Depends(verify_license)):
return {"message": "Access granted", "features": license["features"]}
Flaskβ
from flask import Flask, request, jsonify
from functools import wraps
from quantumlock_sdk import LicenseValidator
app = Flask(__name__)
validator = LicenseValidator()
def require_license(f):
@wraps(f)
def decorated(*args, **kwargs):
license_key = request.headers.get("X-License-Key")
if not license_key:
return jsonify({"error": "License key required"}), 401
result = validator.validate(license_key)
if not result["valid"]:
return jsonify({"error": "Invalid license"}), 401
return f(*args, license=result, **kwargs)
return decorated
@app.route("/protected")
@require_license
def protected(license):
return jsonify({"message": "Access granted", "features": license["features"]})
Node.js SDKβ
Basic Usageβ
const { LicenseValidator } = require('quantumlock-sdk');
const validator = new LicenseValidator();
async function checkLicense(licenseKey) {
const result = await validator.validate(licenseKey);
if (result.valid) {
console.log('β
License is valid');
console.log('Features:', result.features);
console.log('Expires:', result.expires_at);
} else {
console.log('β License is invalid');
}
}
Advanced Usageβ
const { LicenseValidator } = require('quantumlock-sdk');
class LicenseManager {
constructor() {
this.validator = new LicenseValidator({
cacheTTL: 300, // Cache for 5 minutes
offlineMode: false // Online validation
});
}
async checkLicense(licenseKey) {
try {
const result = await this.validator.validate(licenseKey);
if (!result.valid) {
throw new Error('Invalid license');
}
// Check specific features
if (!result.features.includes('premium')) {
throw new Error('Premium feature not enabled');
}
// Check expiration
if (result.days_remaining < 30) {
console.warn(`β οΈ License expires in ${result.days_remaining} days`);
}
return result;
} catch (error) {
console.error('Validation error:', error.message);
return null;
}
}
}
Framework Integrationβ
Expressβ
const express = require('express');
const { LicenseValidator } = require('quantumlock-sdk');
const app = express();
const validator = new LicenseValidator();
// Middleware
async function verifyLicense(req, res, next) {
const licenseKey = req.headers['x-license-key'];
if (!licenseKey) {
return res.status(401).json({ error: 'License key required' });
}
const result = await validator.validate(licenseKey);
if (!result.valid) {
return res.status(401).json({ error: 'Invalid license' });
}
req.license = result;
next();
}
app.get('/protected', verifyLicense, (req, res) => {
res.json({
message: 'Access granted',
features: req.license.features
});
});
Java SDKβ
Basic Usageβ
import com.softquantus.quantumlock.LicenseValidator;
import com.softquantus.quantumlock.ValidationResult;
public class MyApp {
private final LicenseValidator validator = new LicenseValidator();
public void checkLicense(String licenseKey) {
ValidationResult result = validator.validate(licenseKey);
if (result.isValid()) {
System.out.println("β
License is valid");
System.out.println("Features: " + result.getFeatures());
System.out.println("Expires: " + result.getExpiresAt());
} else {
System.out.println("β License is invalid");
}
}
}
Advanced Usageβ
import com.softquantus.quantumlock.*;
public class LicenseManager {
private final LicenseValidator validator;
public LicenseManager() {
this.validator = LicenseValidator.builder()
.cacheTTL(300) // Cache for 5 minutes
.offlineMode(false) // Online validation
.build();
}
public ValidationResult checkLicense(String licenseKey) throws ValidationException {
ValidationResult result = validator.validate(licenseKey);
if (!result.isValid()) {
throw new ValidationException("Invalid license");
}
// Check specific features
if (!result.getFeatures().contains("premium")) {
throw new ValidationException("Premium feature not enabled");
}
// Check expiration
if (result.getDaysRemaining() < 30) {
System.out.println("β οΈ License expires in " + result.getDaysRemaining() + " days");
}
return result;
}
}
Framework Integrationβ
Spring Bootβ
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.softquantus.quantumlock.*;
@Component
public class LicenseInterceptor implements HandlerInterceptor {
private final LicenseValidator validator = new LicenseValidator();
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
String licenseKey = request.getHeader("X-License-Key");
if (licenseKey == null) {
response.setStatus(401);
return false;
}
ValidationResult result = validator.validate(licenseKey);
if (!result.isValid()) {
response.setStatus(401);
return false;
}
request.setAttribute("license", result);
return true;
}
}
@RestController
public class ProtectedController {
@GetMapping("/protected")
public ResponseEntity<?> protectedEndpoint(HttpServletRequest request) {
ValidationResult license = (ValidationResult) request.getAttribute("license");
return ResponseEntity.ok(Map.of(
"message", "Access granted",
"features", license.getFeatures()
));
}
}
C# SDKβ
Basic Usageβ
using QuantumLock.SDK;
public class MyApp
{
private readonly LicenseValidator validator = new LicenseValidator();
public async Task CheckLicense(string licenseKey)
{
var result = await validator.ValidateAsync(licenseKey);
if (result.Valid)
{
Console.WriteLine("β
License is valid");
Console.WriteLine($"Features: {string.Join(", ", result.Features)}");
Console.WriteLine($"Expires: {result.ExpiresAt}");
}
else
{
Console.WriteLine("β License is invalid");
}
}
}
Advanced Usageβ
using QuantumLock.SDK;
public class LicenseManager
{
private readonly LicenseValidator validator;
public LicenseManager()
{
validator = new LicenseValidator(new ValidatorOptions
{
CacheTTL = 300, // Cache for 5 minutes
OfflineMode = false // Online validation
});
}
public async Task<ValidationResult> CheckLicense(string licenseKey)
{
try
{
var result = await validator.ValidateAsync(licenseKey);
if (!result.Valid)
{
throw new ValidationException("Invalid license");
}
// Check specific features
if (!result.Features.Contains("premium"))
{
throw new ValidationException("Premium feature not enabled");
}
// Check expiration
if (result.DaysRemaining < 30)
{
Console.WriteLine($"β οΈ License expires in {result.DaysRemaining} days");
}
return result;
}
catch (ValidationException ex)
{
Console.WriteLine($"Validation error: {ex.Message}");
return null;
}
}
}
Framework Integrationβ
ASP.NET Coreβ
using Microsoft.AspNetCore.Mvc;
using QuantumLock.SDK;
public class LicenseMiddleware
{
private readonly RequestDelegate _next;
private readonly LicenseValidator _validator = new LicenseValidator();
public LicenseMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.Request.Headers.TryGetValue("X-License-Key", out var licenseKey))
{
context.Response.StatusCode = 401;
await context.Response.WriteAsJsonAsync(new { error = "License key required" });
return;
}
var result = await _validator.ValidateAsync(licenseKey);
if (!result.Valid)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsJsonAsync(new { error = "Invalid license" });
return;
}
context.Items["license"] = result;
await _next(context);
}
}
[ApiController]
[Route("protected")]
public class ProtectedController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var license = HttpContext.Items["license"] as ValidationResult;
return Ok(new
{
message = "Access granted",
features = license.Features
});
}
}
Offline Validationβ
All SDKs support offline validation with quantum signature verification:
# Python
validator = LicenseValidator(offline_mode=True)
result = validator.validate(license_key) # No API call
// Node.js
const validator = new LicenseValidator({ offlineMode: true });
const result = await validator.validate(licenseKey);
// Java
LicenseValidator validator = LicenseValidator.builder()
.offlineMode(true)
.build();
// C#
var validator = new LicenseValidator(new ValidatorOptions
{
OfflineMode = true
});
Offline validation verifies:
- β License format
- β Quantum signature integrity
- β Expiration date
- β Feature flags
API Referenceβ
LicenseValidatorβ
Methodsβ
validate(license_key: str) -> dict: Validate a license keyset_cache_ttl(seconds: int): Set cache durationclear_cache(): Clear validation cache
Optionsβ
cache_ttl: Cache duration in seconds (default: 300)offline_mode: Enable offline validation (default: False)timeout: API timeout in seconds (default: 10)
ValidationResultβ
Propertiesβ
valid(boolean): License validitycustomer_id(string): Customer IDend_customer_id(string): End customer IDfeatures(array): Enabled featuresissued_at(datetime): Issue timestampexpires_at(datetime): Expiration timestampdays_remaining(integer): Days until expirationquantum_verified(boolean): Quantum signature statusmetadata(object): Custom metadata
Next Stepsβ
- CLI Reference - Command-line tool
- Deployment Guide - Deploy your own API
- API Reference - REST API documentation