Plumtier Docs Deploy free

Add licensing to your app

The flow most apps want: activate once, validate on launch, stay usable offline, and handle every state.

The flow

  1. First launch, or the user pastes a key: call activate with the key and a device name. On success, save the key and instance.id.
  2. Later launches: call validate with the key and the instance id, at most once a day. Unlock when valid is true.
  3. Offline: if the call fails to reach the store, keep the last good result for a grace period, like 14 days.
  4. Moving to a new device or signing out: call deactivate to free the seat.

A complete example in Swift

LicenseClient.swift
import Foundation

struct LicenseResponse: Decodable {
    struct Key: Decodable { let status: String; let activation_limit: Int?; let activation_usage: Int; let expires_at: String? }
    struct Instance: Decodable { let id: String; let name: String }
    let activated: Bool?
    let valid: Bool?
    let error: String?
    let license_key: Key?
    let instance: Instance?
}

enum LicenseError: Error { case refused(String), offline }

struct LicenseClient {
    let store = URL(string: "https://shop.example.com")!
    let productID = "pastepal"

    private func call(_ path: String, _ fields: [String: String]) async throws -> LicenseResponse {
        var request = URLRequest(url: store.appending(path: "api/v1/licenses/\(path)"))
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONEncoder().encode(fields.merging(["product_id": productID]) { a, _ in a })
        request.timeoutInterval = 10
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            // Every answer, success or not, has the same JSON shape.
            return try JSONDecoder().decode(LicenseResponse.self, from: data)
        } catch {
            // No connection, a timeout, or a page that isn't the store: not a refusal.
            throw LicenseError.offline
        }
    }

    func activate(key: String, deviceName: String) async throws -> String {
        let response = try await call("activate", ["license_key": key, "instance_name": deviceName])
        guard response.activated == true, let instance = response.instance else {
            throw LicenseError.refused(response.error ?? "This key can't be activated.")
        }
        return instance.id
    }

    func validate(key: String, instanceID: String) async throws -> Bool {
        let response = try await call("validate", ["license_key": key, "instance_id": instanceID])
        if response.valid == true { return true }
        throw LicenseError.refused(response.error ?? "This key isn't valid any more.")
    }

    func deactivate(key: String, instanceID: String) async throws {
        _ = try await call("deactivate", ["license_key": key, "instance_id": instanceID])
    }
}

The same in JavaScript

For Electron apps, browser extensions and web apps:

license.js
const STORE = "https://shop.example.com";
const PRODUCT = "pastepal";
const GRACE_DAYS = 14;

// saveLicense and loadLicense are yours: keep the key somewhere safe, like the OS keychain.

async function call(path, fields) {
  const response = await fetch(`${STORE}/api/v1/licenses/${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ ...fields, product_id: PRODUCT }),
    signal: AbortSignal.timeout(10_000),
  });
  return response.json(); // same shape for success and failure
}

export async function activate(key, deviceName) {
  const result = await call("activate", { license_key: key, instance_name: deviceName });
  if (!result.activated) throw new Error(result.error);
  saveLicense({ key, instanceId: result.instance.id, checkedAt: Date.now() });
}

export async function isLicensed() {
  const saved = loadLicense();
  if (!saved) return false;
  try {
    const result = await call("validate", { license_key: saved.key, instance_id: saved.instanceId });
    if (result.valid) saveLicense({ ...saved, checkedAt: Date.now() });
    return result.valid;
  } catch {
    // Offline or the store is unreachable: trust the last good check for a while.
    return Date.now() - saved.checkedAt < GRACE_DAYS * 86_400_000;
  }
}

What to show for each answer

AnswerSuggested app behavior
valid: trueUnlock. Save the time of the check.
Activation limit reachedSay how many devices the key allows, and link to https://shop.example.com/portal where the buyer can free one.
expiredSay so, and link to renew or buy again.
disabledLock. The order was refunded or you turned the key off.
HTTP 404The key doesn't exist, or the instance was removed. Ask for the key again.
Can't reach the storeUse the last good check within your grace period.

Good habits

  • Validate at most once a day and when the user opens your license window. There's no need to call on every action.
  • Store the key in the keychain or your platform's secure storage, not in plain preferences.
  • Use a stable, readable device name, like the computer's name. Buyers see it when they choose which device to free.
  • Always send product_id so keys for your other products don't unlock this one.
  • Don't treat a failed request as a refusal. Only a response that says valid: false is a no.