Skip to main content

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 key
  • set_cache_ttl(seconds: int): Set cache duration
  • clear_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 validity
  • customer_id (string): Customer ID
  • end_customer_id (string): End customer ID
  • features (array): Enabled features
  • issued_at (datetime): Issue timestamp
  • expires_at (datetime): Expiration timestamp
  • days_remaining (integer): Days until expiration
  • quantum_verified (boolean): Quantum signature status
  • metadata (object): Custom metadata

Next Steps​