The check, as a coroutine
Unity’s web request API is asynchronous. yield return request.SendWebRequest() hands control back to the engine until the request finishes. The License API accepts form bodies, so WWWForm is enough and no JSON writer is needed.
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
[Serializable] public class LicenseInfo { public int id; public string status; public int activation_limit; public int activation_usage; }
[Serializable] public class ValidateReply { public bool valid; public string error; public string token; public LicenseInfo license_key; }
[Serializable]
public class SavedLicense
{
public string key, instance, token;
public long highIat; // used by the offline check
static string FilePath => Path.Combine(Application.persistentDataPath, "license.json");
public static SavedLicense Load() { try { return JsonUtility.FromJson<SavedLicense>(File.ReadAllText(FilePath)); } catch { return null; } }
public void Save() { File.WriteAllText(FilePath, JsonUtility.ToJson(this)); }
public static void Clear() { try { File.Delete(FilePath); } catch { } }
}
public enum LicenseState { Unlicensed, Licensed, Invalid, NeedsNetwork }
public class LicenseChecker : MonoBehaviour
{
const string Base = "https://clavem.io";
static bool started;
public static LicenseState State = LicenseState.Unlicensed;
public static event Action<LicenseState> Changed;
// With "Reload Domain" turned off for faster play mode, statics survive between runs.
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStatics() { started = false; }
void Awake()
{
if (started) { Destroy(gameObject); return; } // a second copy arrived with another scene
started = true;
DontDestroyOnLoad(gameObject);
#if UNITY_EDITOR
Set(LicenseState.Licensed); // development: play mode does not call the License API
#else
StartCoroutine(Run());
#endif
}
IEnumerator Run()
{
var saved = SavedLicense.Load();
if (saved == null) { Set(LicenseState.Unlicensed); yield break; }
var form = new WWWForm();
form.AddField("license_key", saved.key);
form.AddField("instance_id", saved.instance);
using (var req = UnityWebRequest.Post(Base + "/v1/licenses/validate", form))
{
req.timeout = 8; // seconds
yield return req.SendWebRequest();
long status = req.responseCode; // 0 when no HTTP answer came back
// 400, 404, 429 and 503 finish as ProtocolError. The JSON body is still in downloadHandler.
ValidateReply reply = status == 0 ? null : Parse(req.downloadHandler.text);
if (status == 200 && reply != null)
{
if (!string.IsNullOrEmpty(reply.token)) { saved.token = reply.token; saved.Save(); }
Set(reply.valid ? LicenseState.Licensed : LicenseState.Invalid);
yield break;
}
if (status == 404) { SavedLicense.Clear(); Set(LicenseState.Invalid); yield break; }
// 0, 400, 429, 5xx: no usable answer. Trust the stored token while it is fresh.
if (status == 429) Debug.Log("License API busy, Retry-After " + req.GetResponseHeader("Retry-After"));
Set(OfflineToken.IsFresh(saved) ? LicenseState.Licensed : LicenseState.NeedsNetwork);
}
}
static ValidateReply Parse(string json)
{
try { return JsonUtility.FromJson<ValidateReply>(json); } catch (ArgumentException) { return null; }
}
static void Set(LicenseState s) { State = s; Changed?.Invoke(s); }
}
OfflineToken.IsFresh is on the offline page. Put the component on a GameObject in your first scene.
Reading the result
request.result |
responseCode |
Meaning |
|---|---|---|
Success |
200 | Read valid. false means expired or disabled; show error. |
ProtocolError |
404 | Unknown key, or this device’s activation was removed. Clear and ask for the key. |
ProtocolError |
400 | Your request is malformed. Log it, use the stored token. |
ProtocolError |
429 | Rate limited, Retry-After: 60. Use the stored token. |
ProtocolError |
503 | Our side, Retry-After: 5. Use the stored token. |
ConnectionError |
0 | Offline, DNS or TLS failure, or timeout. Use the stored token. |
DataProcessingError |
any | The body was corrupt. Treat as no answer. |
Do not test request.result == Success alone. It is false for a 404, which is a perfectly good answer.
A captured real response, 19 November 2026, for a request that sends no license_key:
POST /v1/licenses/validate (no license_key)
400 {"valid":false,"error":"license_key: Invalid input: expected string, received undefined"}
Unity-specific traps
- Never wait in a loop.
while (!op.isDone) { }freezes the game. In a Web build the browser’s Fetch API does the work, so a blocking wait on the main thread can never finish. - Scene loads.
Awakeruns again for every scene that contains the object. Thestartedflag andDontDestroyOnLoadkeep it to one call per process, which matters with a limit of 60 requests a minute per key. - Paused games. If you retry after a delay, use
WaitForSecondsRealtime. WithTime.timeScaleat 0,WaitForSecondsnever finishes. JsonUtilitycannot tell null from missing. Anactivation_limitofnull(unlimited) reads as0, so treat0as unlimited, and test strings withstring.IsNullOrEmpty.- Editor tools. Coroutines are unreliable in edit mode. In an editor window, attach a callback to
request.SendWebRequest().completedinstead.
Where to keep the key
PlayerPrefs is a poor home. Unity’s documentation says it is stored unencrypted and should not hold sensitive data. A file in Application.persistentDataPath is no safer from the person at the keyboard, and you cannot hide a key from the buyer who owns it. Protect integrity, not secrecy: the signed token cannot be edited without breaking its signature, and a corrupt or missing file simply means asking for the key again, as Load does.
Doing this with Clavem
The License API takes the key as the credential, with no secret in the game. The token this call returns is what lets a player keep playing offline, as shown in offline verification in Unity. Activation and seats are on the device activation page. The status model is in the API reference.
Questions
Can I call validate from a background thread?
Do not. UnityWebRequest and JsonUtility belong on the main thread. A coroutine that yields on SendWebRequest keeps the game running while the request is in flight, and nothing blocks.
Should validation run in the Editor?
Not as a paying customer would. Guard it with UNITY_EDITOR, as the sample does, so play mode neither calls the License API on every run nor needs a real key.