Skip to content

SDKs ​

Official, open-source clients live at github.com/sunlicense-com. They all use the same two settings:

SettingValue
Base URLhttps://api.sunlicense.com
Tokenan API key from Dashboard → API keys (slk_…)

The examples read the API key from the SUNLICENSE_API_KEY environment variable (or, in FiveM, the sunlicense_api_key convar). Keep it apart from SUNLICENSE_TOKEN, which holds a personal access token (slp_…) for the CLI and AI assistants: that one can manage your organization and never belongs in an app.

Every SDK calls POST /api/v2/license/validate. HTTP 200 means valid; 400 means rejected, and the body's code says why (result codes). Pass a stable machine id as host so machine limits work.

java
// implementation 'com.sunlicense:sunlicense:0.0.1'
SunLicense client = new SunLicense.Builder()
        .baseUrl("https://api.sunlicense.com")
        .token(System.getenv("SUNLICENSE_API_KEY"))
        .build();

SunLicense.Result result = client.validate(licenseKey, Map.of("host", machineId));
if (!result.isValid()) { /* result.getBody() has the code */ }
js
// npm install sunlicense
import { SunLicense } from "sunlicense";

const client = new SunLicense({ baseUrl: "https://api.sunlicense.com", token: process.env.SUNLICENSE_API_KEY });
const result = await client.validate(licenseKey, { host: machineId });
python
# pip install sunlicense
import os
import platform

from sunlicense import SunLicense

client = SunLicense(base_url="https://api.sunlicense.com", token=os.environ["SUNLICENSE_API_KEY"])
result = client.validate(license_key, host=platform.node())
csharp
// dotnet add package SunLicense
using var client = new SunLicenseClient("https://api.sunlicense.com",
    token: Environment.GetEnvironmentVariable("SUNLICENSE_API_KEY"));
var result = await client.ValidateAsync(licenseKey, new Dictionary<string, string> { ["host"] = machineId });
php
// composer require sunlicense/sunlicense
$client = new SunLicenseClient('https://api.sunlicense.com', token: getenv('SUNLICENSE_API_KEY'));
$result = $client->validate($licenseKey, ['host' => $machineId]);
lua
-- luarocks install sunlicense (or drop sunlicense.lua into your FiveM/GMod resource)
local SunLicense = require("sunlicense")
local client = SunLicense.new({ baseUrl = "https://api.sunlicense.com", token = GetConvar("sunlicense_api_key", "") })
client:validate(licenseKey, { host = GetConvar("sv_hostname", "") }, function(ok, status, body) end)

The Rust client (cargo add sunlicense) currently provides configuration only; validation is coming.

Writing a Minecraft plugin or mod, a FiveM resource or a Discord bot? Start from a template: the SDK, store placeholders, messages and an offline fallback, ready to build.

Using an AI coding assistant? Use SunLicense with your AI assistant has one prompt that sets everything up in any language, and the docs in a format assistants read well.

Built-in analytics ​

Every official SDK (Java, JavaScript, Python, .NET, PHP and Lua, from 0.1.0; the templates already) reports anonymous usage statistics for the product's Analytics tab: which versions of your product people run, on which OS, runtime and platform, like bStats. You write no code beyond starting it; it never runs on the license check's path, never delays or fails a check, and swallows its own errors.

java
// A licensed product: the same API key, license key and machine id it validates with.
SunLicenseAnalytics analytics = SunLicenseAnalytics.builder()
        .apiKey(System.getenv("SUNLICENSE_API_KEY")).licenseKey(licenseKey).fingerprint(machineId)
        .productVersion("2.3.1")
        .enabled(config.getBoolean("analytics", true))   // your config's switch
        .start();

// A free product, no license: its public product analytics id (Product → Analytics).
SunLicenseAnalytics analytics = SunLicense.analytics("pa_7Hk2mQ9xZr4LbN8vT1wYcD");

analytics.close();   // on shutdown, e.g. a plugin's onDisable
js
// Licensed: the client's base URL and API key, plus the license key and machine id it validates with.
const analytics = client.analytics({ licenseKey, fingerprint: machineId, productVersion: '2.3.1',
                                     enabled: config.analytics !== false });

// Free: the product analytics id. The install id lives in a hidden per-user dir by default (defaultStateDir()).
const analytics = SunLicense.analytics('pa_7Hk2mQ9xZr4LbN8vT1wYcD');

analytics.close();   // on shutdown (its timers never keep the process alive)
python
# Licensed
analytics = client.analytics(license_key, machine_id, product_version="2.3.1",
                             enabled=config.get("analytics", True))

# Free
analytics = SunLicense.analytics_for("pa_7Hk2mQ9xZr4LbN8vT1wYcD", data_directory="data")

analytics.close()   # on shutdown (it runs on a daemon thread)
csharp
// Licensed
using var analytics = client.Analytics(licenseKey, machineId,
    new SunLicenseAnalyticsOptions { ProductVersion = "2.3.1", Enabled = config.Analytics });

// Free
using var analytics = SunLicenseAnalytics.ForProduct("pa_7Hk2mQ9xZr4LbN8vT1wYcD");
php
// Licensed. PHP has no background thread: a due report is sent after the script ends (at most every 30 minutes),
// and its schedule is kept in dataDirectory.
$analytics = $client->analytics(['licenseKey' => $key, 'fingerprint' => $machineId,
                                 'productVersion' => '2.3.1', 'dataDirectory' => __DIR__ . '/storage']);

// Free
$analytics = SunLicenseAnalytics::forProduct('pa_7Hk2mQ9xZr4LbN8vT1wYcD', ['dataDirectory' => __DIR__ . '/storage']);
lua
-- Licensed (FiveM, RedM, Garry's Mod; plain Lua calls analytics:poll() from its main loop)
local analytics = client:analytics({ licenseKey = key, fingerprint = machineId,
                                     enabled = GetConvar("myresource_analytics", "true") ~= "false" })

-- Free
local analytics = SunLicense.analytics("pa_7Hk2mQ9xZr4LbN8vT1wYcD")

The first report goes 1 to 30 minutes after start (random, so a fleet restarted together doesn't report together), then one every 30 minutes to POST /api/v2/analytics/report. When SunLicense answers with Retry-After (analytics switched off for the product, rate limits) the SDK waits that long, at most 24 hours.

What is sent (raw values; SunLicense groups them, e.g. 5.15.0-1051-oracle into Linux 5.15):

FieldExampleWhere it comes from
productVersion2.3.1What you pass as the product version; the templates use their build version (FiveM: fxmanifest.lua's version)
os, osVersionLinux, 5.15.0-1051-oracleThe runtime's OS name and version (FiveM: from the server build string; Garry's Mod: the OS family only)
archaarch64The CPU architecture, where the runtime tells it
cores4Processors available to the runtime, where it tells them
localeen_USThe default locale
runtime, runtimeVersionjava, 21.0.4See the table below
platform, platformVersionpaper, 1.21.1-R0.1-SNAPSHOTDetected, see the table below; every SDK lets you override it
sdkjava 0.1.0The SDK's name and version
IdentityLicensed: the license key and machine id, with the API key. Free: the product analytics id and a random install id kept in a hidden per-user directory (where SDK state lives), one file per product — never next to the product
SDKRuntimePlatforms it detects (else standalone)
Javajava + java.versionPaper, Spigot, Purpur, Folia and other Bukkit servers (by their own name), BungeeCord, Waterfall, Velocity, Sponge, Fabric, Quilt, Forge, NeoForge (the Minecraft version), a Discord bot on JDA or Javacord (the library's version)
JavaScriptnode, bun or deno + versionfivem/redm (server build), electron, discord (discord.js, Eris, Oceanic or Discordeno installed: its version)
Pythonpython + versiondiscord (discord.py, nextcord, disnake, interactions.py or hikari imported: its version)
.NETdotnet or mono + versionfivem/redm (CitizenFX loaded: the server build), discord (Discord.Net, DSharpPlus, NetCord, Remora), unity
PHPphp + PHP_VERSIONwordpress, laravel, symfony (with their version)
Lualua (luajit on Garry's Mod) + versionfivem/redm (the server build, e.g. 7290), gmod

The country comes from Cloudflare's edge, not from the SDK; no IP address is stored. Nothing personal is sent: no user, host, server or player names, IP addresses or file paths.

Switching it off. Nothing is sent, not even an empty report, when any of these says so, checked before every report:

  • your product's own setting: enabled(false) / enabled: false / Enabled = false (the templates' analytics: false, ANALYTICS=false in the bot's .env, set my_resource_analytics false on FiveM);
  • the environment variable SUNLICENSE_ANALYTICS=off (also false or 0), for every product on the machine;
  • the platform's global switch: the system property -Dsunlicense.analytics=false (Java), the runtime setting sunlicense.analytics (.NET runtimeconfig.json), the constant SUNLICENSE_ANALYTICS defined as false (PHP), the convar sunlicense_analytics (FiveM, every SunLicense resource on the server) or the global SUNLICENSE_ANALYTICS = false (Lua).

Feature usage and custom charts ​

Count how often your features are used and add your own charts, bStats' chart types. Feature uses are counted in memory and sent with the next report, kept until one is accepted and dropped while analytics is off; chart callbacks run just before each report, and one that throws or returns nothing is left out. Names and chart ids: [a-z0-9][a-z0-9._-]{0,47}; at most 50 different features and 30 charts per report. A report that would pass 16 KB leaves out the charts first, then the features.

java
analytics.feature("auto-sell");
analytics.simplePie("storage", () -> config.getString("storage"))
         .singleLine("players", () -> Bukkit.getOnlinePlayers().size());
js
analytics.feature('auto-sell');
analytics.simplePie('storage', () => config.storage)
         .singleLine('servers', () => client.guilds.cache.size);
python
analytics.feature("auto-sell")
analytics.simple_pie("storage", lambda: config["storage"]).single_line("servers", lambda: len(bot.guilds))
csharp
analytics.Feature("auto-sell");
analytics.SimplePie("storage", () => config.Storage).SingleLine("players", () => Players.Count);
php
$analytics->feature('auto-sell');
$analytics->simplePie('storage', fn () => $config['driver'])->singleLine('users', fn () => $userCount);
lua
analytics:feature("auto-sell")
analytics:simplePie("framework", function() return Config.Framework end)
         :singleLine("players", function() return #GetPlayers() end)
ChartCallback returnsJava / JS / PHP / LuaPython.NET
Simple piea value ("mysql")simplePiesimple_pieSimplePie
Advanced pieweighted values ({mysql: 2, sqlite: 1})advancedPieadvanced_pieAdvancedPie
Drilldown pievalues with a second level ({"Java 21": {"21.0.4": 1}})drilldownPiedrilldown_pieDrilldownPie
Single linea number, summed over installssingleLinesingle_lineSingleLine
Multi lineseveral numbers ({overworld: 30, nether: 12})multiLinemulti_lineMultiLine
Simple barnumbers per categorysimpleBarsimple_barSimpleBar
Advanced barseveral numbers per category ({gold: [1, 2, 3]})advancedBaradvanced_barAdvancedBar

removeChart(id) stops sending one. Feature usage and custom charts show up on the Lite and Standard plans (product analytics); the reports are the same on every plan.

Protection: core unlock, tamper reports, notice, protected files ​

Part of your product can be made to run only with a valid license, so a copy whose license check was deleted (by a cracker or an AI editor asked to "remove the license check") has nothing to run. Every SDK does it the same way (Java; JavaScript, Python, .NET, PHP and Lua from 0.2.0). The honest limit: someone with a valid license can still pull the key out of memory and patch their copy; that copy then reports itself as modified, and download watermarks name the leaker. How it fits together, and the steps without an SDK: Protection.

PieceWhat the SDK does
Core unlocksunlicense seal encrypts the core at build time (an SLS1.… blob). A valid check's answer carries unlock, the key that opens it; unseal(blob) returns the core. A rejected check (suspended, expired, revoked…) carries none and makes the SDK forget the one it had
OutagesThe unlock from the last valid check is kept for 7 days, encrypted with a key from the license key, the machine id and this machine, so a copied cache file is useless elsewhere. An offline license file carries it too (Java, JavaScript, Python, PHP)
Tamper reportsThe seal can carry SHA-256 digests of your other files. integrity(…) compares them with what's running and the result (OK or MODIFIED, plus up to 200 characters of which files) goes with the next license check, where Sentinel sees it
Ownership noticenotice() is one start-up log line: product, owner, the masked key and your terms link. Never the buyer's name or a full key
Protected filesprotectedFile(name) downloads a file you uploaded to the product (Standard plan); SunLicense sends it only while the license is valid
bash
sunlicense seal core.lua --product my-resource -o core.sealed --digest fxmanifest.lua
java
// SunLicenseProtection: one dependency-free file (Java 11+), see Single-file sources below. Copy it; don't edit it.
SunLicenseProtection protection = SunLicenseProtection.builder()
        .apiKey(apiKey).licenseKey(licenseKey).fingerprint(machineId)
        .product("MyPlugin", "Example Studio").terms("https://example.com/terms")
        .productCode("myplugin")                 // for protected files
        // the 7-day unlock cache lives in a hidden per-user dir by default (defaultStateDir()), not next to your
        // product; call .cacheDirectory(...) only to put it somewhere specific
        .build();
log.info(protection.notice());                   // "MyPlugin is licensed software by Example Studio. License AX8P-XXXX-…"

Map<String, String> context = new LinkedHashMap<>(Map.of("host", machineId));
context.putAll(protection.validateFields());     // integrity: OK / MODIFIED, once the jar was checked
SunLicense.Result r = client.validate(licenseKey, context);
if (r.isValid()) protection.accept(r.getBody());           // keeps (and caches) the unlock
else if (r.getStatus() == 400) protection.rejected();      // a "no": the unlock is gone
// Offline fallback: protection.acceptOffline(licFile, publicKey) takes the .lic file's unlock.

byte[] core = protection.unseal(SEALED_CORE);              // throws Locked without a valid unlock
protection.integrity(MyPlugin.class.getClassLoader());     // OK / MODIFIED, sent with the next check
ClassLoader coreClasses = SunLicenseProtection.classLoader(core, MyPlugin.class.getClassLoader());
byte[] rules = protection.protectedFile("rules.dat");      // Standard plan
js
const protection = client.protection({ licenseKey, fingerprint: machineId, product: 'My Bot',
  owner: 'Example Studio', terms: 'https://example.com/terms' });   // unlock cache: hidden per-user dir by default
console.log(protection.notice());
await client.validate(licenseKey, { fingerprint: machineId }); // sends integrity, keeps or forgets the unlock
const core = protection.unseal(SEALED_CORE);                    // throws Locked without a valid unlock
protection.integrity(appDir);                                   // 'OK' / 'MODIFIED', sent with the next check
python
protection = client.protection(license_key=key, fingerprint=machine_id, product="My Bot",
                               owner="Example Studio", terms="https://example.com/terms", cache_directory="data")
print(protection.notice())
client.validate(key, fingerprint=machine_id)   # sends integrity, keeps or forgets the unlock
core = protection.unseal(SEALED_CORE)          # raises Locked without a valid unlock
protection.integrity(app_dir)                  # "OK" / "MODIFIED", sent with the next check
csharp
var protection = client.Protection(new SunLicenseProtectionOptions {
    LicenseKey = key, Fingerprint = machineId, Product = "My App", Owner = "Example Studio",
    Terms = "https://example.com/terms", CacheDirectory = dataFolder });
Console.WriteLine(protection.Notice());
await client.ValidateAsync(key, new Dictionary<string, string> { ["fingerprint"] = machineId });
byte[] core = protection.Unseal(SealedCore);   // throws SunLicenseLockedException without a valid unlock
protection.Integrity(AppContext.BaseDirectory); // "OK" / "MODIFIED", sent with the next check
php
$protection = $client->protection(['licenseKey' => $key, 'fingerprint' => $machineId, 'product' => 'My Plugin',
    'owner' => 'Example Studio', 'terms' => 'https://example.com/terms', 'cacheDirectory' => $dataDir]);
error_log($protection->notice());
$client->validate($key, ['fingerprint' => $machineId]); // sends integrity, keeps or forgets the unlock
$core = $protection->unseal(SEALED_CORE);               // throws LockedException without a valid unlock
$protection->integrity(__DIR__);                        // 'OK' / 'MODIFIED', sent with the next check
lua
local protection = client:protection({ licenseKey = key, fingerprint = machineId, product = "My Script",
  owner = "Example Studio", terms = "https://example.com/terms" })
print(protection:notice())
client:validate(key, { fingerprint = machineId }, function(ok)
  local core, err = protection:unseal(LoadResourceFile(GetCurrentResourceName(), "core.sealed"))
  if core then load(core, "@core")() end           -- nil + reason without a valid unlock
  protection:integrity()                            -- "OK" / "MODIFIED", sent with the next check
end)

The Java templates do all of this for you: their core package is sealed in release builds (./gradlew build -PsunlicenseProduct=<code>, which calls sunlicense seal on the final jar and digests your other classes), loaded through license/SealedCore.java, and the notice is logged at start-up. Apps that use none of it behave exactly as before: no integrity is sent and nothing is cached until a product has sealed data.

The FiveM and discord.js templates seal server/core.lua and src/core.js the same way (SUNLICENSE_PRODUCT=<code> when you run scripts/package.sh or npm run build) and log the notice at start-up.

Without a native AES-GCM the SDKs bring their own: pure Lua on FiveM, Garry's Mod and plain Lua; pure Python when cryptography isn't installed; the platform's AES block cipher on .NET (netstandard2.0, Mono, Unity, CitizenFX). PHP needs ext-openssl (or ext-sodium on a CPU with AES). Digest files that don't contain the sealed text itself, and on FiveM only files Tebex's escrow leaves readable.

Single-file sources ​

Some SDK classes are one file with no dependencies, so you can copy them into a project whose installed SDK release doesn't have them yet. Copy the current file and change only its package line; don't write it yourself from these pages. Each file is built from the SDK on every docs release:

LanguageClassFile
Java 11+SunLicenseProtection (core unlock, tamper reports, notice, protected files, offline unlock)/sdk/java/SunLicenseProtection.java
Java 11+SunLicenseAnalytics (built-in analytics)/sdk/java/SunLicenseAnalytics.java

The templates carry the same files in their license/ folder. Other SDKs: install the latest release, or for Lua copy sunlicense.lua, which is one file already (the FiveM template's lib/sunlicense.lua).

Choosing a machine id ​

Use something stable across reboots and updates: a hash of hardware identifiers, or an id you generate once and store. Don't use the IP address. The Java CLI's fingerprint command shows one approach.

Prefer an id derived from host facts over one you store, so there is no file to leave next to your product. The Java SDK exposes SunLicenseProtection.machineId() (OS, architecture, hostname and MAC addresses, hashed) and the JavaScript SDK exports machineId(); the templates use these. If you do store an id, keep it in a hidden per-user directory (see below), not the product's own folder.

Where SDK state lives ​

By default the SDKs keep their state — the 7‑day unlock cache, the analytics install id, and any machine id you store — in a hidden per-user directory, never next to your product, so there is nothing for an end user to see or delete:

OSDirectory
Linux / other$XDG_CACHE_HOME/sunlicense or ~/.cache/sunlicense
macOS~/Library/Caches/SunLicense
Windows%LOCALAPPDATA%\SunLicense

Falling back to ~/.sunlicense, then the system temp directory. It is one small file per product. The Java SDK exposes the directory as SunLicenseProtection.defaultStateDir() / SunLicenseAnalytics.defaultStateDir(); the JavaScript SDK exports defaultStateDir(). If you set cacheDirectory / dataDirectory explicitly, the SDK writes a single file there instead. When an older build kept an id next to the product (a .server-id, .machine-id or .sunlicense-install-id), the SDK carries that value into the hidden directory once and removes the old file, so installs keep their machine slot. Anything that can't reach an OS directory (a FiveM resource, which may only use LoadResourceFile/SaveResourceFile) keeps a single file inside the resource folder instead, and says so.

Handling errors ​

HTTPMeaningRecommended behaviour
200ValidContinue
400Rejected (see code)Block or prompt, depending on the code
401Missing or wrong API keyA configuration bug in your app
429Rate limitedRetry later
5xx / network errorSunLicense is unreachableFall back to the offline license

Send feedback

Found something broken, or have an idea? It goes straight to our board.

The first line becomes the title.
Images (optional, up to 5: paste, drop or capture)
Check each image before sending, and remove any that show something private.

We also receive this page's address and your browser version.

Ctrl Enter to send