The LicenseAPI

You can get access to the LicenseAPI via the support. There you can also ask for your Product-ID.

Have license keys generated automatically

Create license generator

First you need to create a license generator. This can be done in the developer dashboard here. By pressing "Add new generator" you can now create a generator.

A name and a maximum number of activations are required. In most cases, 0 is specified here for no limit.

Then you specify a character map, which are all characters that should be included in the license key. e.g. abcdefghijklmnopqrstowv etc.

After that, the blocks of the license key can be configured. The number, the length and the separators can be defined individually. A prefix or suffix for the license key can also be set.

In the last field "Expires in" you do not make any entries, because our license keys should be permanent.

Activate and send license key in the product

Once you have created the generator, you can easily generate and send license keys automatically. To do this, you need to edit your product and click on "License management" under Description. There you can activate the sale of license keys for the product and select the number and the generator. The sale from stock must be deactivated.

Application example
String licenseKey = mainConfiguration.getString("License");
try {
this.licenseAPI = new LicenseAPI(<productId>,<consumerKey>, <consumerSecretkey>, plugin.getDataFolder());
this.licenseAPI.checkLicense(licenseKey);
this.continuePlugin = true;
System.out.println("[" + this.getPlugin().getName() + "] Valid License Key!");
System.out.println("[" + this.getPlugin().getName() + "] You can view your key informations here: https://www.yourmcshop.com/myaccount/view-license-keys/");
} catch (Throwable ex) {
if(ex instanceof LicenseAPI.LicenseError) {
LicenseAPI.LicenseError licenseError = (LicenseAPI.LicenseError) ex;
if(licenseError.shouldContinuePlugin()) {
System.out.println("[" + this.getPlugin().getName() + "] Valid License Key!");
System.out.println("[" + this.getPlugin().getName() + "] Cannot connect to license server...");
return;
}
}
String licensePath = mainConfiguration.getFile().getPath().replace("", "/");
System.out.println("[" + this.getPlugin().getName() + "] Your License Key '" + licenseKey + "' is wrong! Please check " + licensePath);
System.out.println("[" + this.getPlugin().getName() + "] " + ex.getMessage());

String kickMessage = "§4Wrong License Key!nn§4Check " + licensePath;

Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage));
Bukkit.getServer().getPluginManager().registerEvents(new org.bukkit.event.Listener() {
@EventHandler
public void onJoin(PlayerLoginEvent e) {
e.disallow(PlayerLoginEvent.Result.KICK_OTHER, kickMessage);
}
}, this.plugin);
}

LicenseAPI.class

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Properties;

public class LicenseAPI {

    /**
     * This is the LicenseAPI class of YourMcShop.com
     * The methods should be self-explanatory.
     * Just create a new instance of the LicenseAPI class and pass your consumer keys and the folder of the plugin.
     * (You can get the consumer keys from the support of YourMcShop.com)
     * After that you can simply execute the checkLicense method.
     * It throws an error when something is not working correctly and you can catch this error.
     */

    private final List<Integer> productIds;
    private final String consumerKey;
    private final String consumerSecret;
    private final File dataFolder;

    public LicenseAPI(List<Integer> productIds, String consumerKey, String consumerSecret, File dataFolder) {
        this.productIds = productIds;
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.dataFolder = dataFolder;
    }

    public void checkLicense(String licenseKey) throws Throwable {
        if(licenseKey == null) {
            throw new LicenseError("The License key is null!");
        }
        if(licenseKey.length() < 10) {
            throw new LicenseError("The License key is too short!");
        }

        boolean checkValid = false;

        try {
            File file = new File(this.dataFolder,".cachedyms");
            if(file.exists()) {
                Properties properties = new Properties();
                FileInputStream fileInputStream = new FileInputStream(file);
                properties.load(fileInputStream);
                fileInputStream.close();
                if(properties.getProperty(licenseKey) != null && properties.getProperty(licenseKey).equalsIgnoreCase("true")) {
                    checkValid = true;
                }
            } else {
                activateLicense(licenseKey);
            }
        } catch (IOException ex) {
            System.out.println("Error while loading key file...");
        }

        if(checkValid) {
            validateLicense(licenseKey);
        } else {
            activateLicense(licenseKey);
        }
    }

    private void activateLicense(String license)throws Throwable {
        String request = String.format("https://www.yourmcshop.com/wp-json/lmfwc/v2/licenses/activate/%s", license);
        JsonObject response = doPostCall(request);
        JsonElement result = response.get("success");
        if(result == null || !result.isJsonPrimitive())
            throw new LicenseError("Cannot connect with the license server...");

        if (!result.getAsBoolean())
            throw new LicenseError("Activation of license failed!");

        if(!this.productIds.contains(response.getAsJsonObject("data").get("productId").getAsInt())) {
            throw new LicenseError("Activation of license failed - Wrong license for this product!");
        }

        File file = new File(this.dataFolder,".cachedyms");
        if(!file.exists()) {
            file.createNewFile();
        }
        Properties properties = new Properties();
        properties.setProperty(license, "true");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        properties.store(fileOutputStream, null);
        fileOutputStream.close();
    }

    private void validateLicense(String license) throws Throwable {
        String request = String.format("https://www.yourmcshop.com/wp-json/lmfwc/v2/licenses/validate/%s", license);
        JsonObject response;
        try {
            response = doPostCall(request);
        } catch (LicenseError licenseError) {
            if(licenseError.getMessage().equalsIgnoreCase("Could not reach license server!")) {
                throw new LicenseError(licenseError.getMessage(), true);
            } else {
                throw licenseError;
            }
        }
        JsonElement result = response.get("success");

        if(result == null || !result.isJsonPrimitive())
            throw new LicenseError("Cannot connect with the license server...", true);

        if (!result.getAsBoolean())
            activateLicense(license);
    }

    private JsonObject doPostCall(String urlQueryString) throws Throwable {
        JsonObject json;
        HttpsURLConnection connection = openConnection(urlQueryString);

        try {
            connection.setRequestMethod("GET");
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        }
        byte[] encodedAuth = Base64.getEncoder().encode((consumerKey + ":" + consumerSecret).getBytes(StandardCharsets.UTF_8));
        connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuth));
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Host", InetAddress.getLocalHost().toString());
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);

        try {
            connection.connect();
        } catch (IOException e) {
            throw new LicenseError("Could not reach license server!");
        }

        if(connection.getResponseCode() == 200) {
            String inputLine;
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                Gson gson = new Gson();
                JsonElement element = gson.fromJson(response.toString(), JsonElement.class);
                json = element.getAsJsonObject();
            } catch (IOException ex) {
                throw new LicenseError("Failed to receive license information!");
            }
        } else if(connection.getResponseCode() == 404) {
            throw new LicenseError("Activation of license failed!");
        } else {
            throw new LicenseError("Could not talk to license server! " + connection.getResponseCode() + " - " + connection.getResponseMessage());
        }
        return json;
    }

    private HttpsURLConnection openConnection(String urlQueryString) throws Throwable{
        URL url;
        try {
            url = new URL(urlQueryString);
        } catch (MalformedURLException e) {
            throw new LicenseError("Address of license server malformed!");
        }
        try {
            return (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            throw new LicenseError("Could not reach license server!");
        }
    }

    public static class LicenseError extends Error {

        private boolean continuePlugin = false;

        public LicenseError(String message) {
            super(message);
        }

        public LicenseError(String message, boolean continuePlugin) {
            super(message);
            this.continuePlugin = continuePlugin;
        }

        public boolean shouldContinuePlugin() {
            return continuePlugin;
        }
    }
}

Enter our Discord for updates.