Die LicenseAPI

Zugang zur LicenseAPI bekommt man über den Support. Dort könnt ihr auch eure Product-ID erfragen.

Lizenzschlüssel automatisch generieren lassen

Lizenz Generator erstellen

Zunächst muss ein Lizenz Generator erstellt werden. Das geht im Entwickler Dashboard hier. Durch das Drücken auf “Neuen Generator hinzufügen” kann man jetzt einen Generator erstellen.

Dabei wird ein Name verlangt und eine maximale Anzahl von Aktiviereungen. In den meisten Fällen gibt man hier 0 für keine Begrenzung an.

Danach gibt man eine Zeichenkarte an, das sind alle Zeichen die im Lizenzschlüssel enthalten sein sollen. z.B. abcdefghijklmnopqrstowv usw

Danach lassen sich die Blöcke des Lizenzschlüssels konfigurieren. Die Anzahl, die Länge und die Trennzeichen kann man dort individuell festlegen. Auch ein Prefix oder Suffix für den Lizenzschlüssel lässt sich einstellen.

Beim letzten Feld “Läuft ab in” macht man keine Angaben, da unsere Lizenzschlüssel permanent sein sollen.

Lizenzschlüssel im Produkt aktivieren und versenden

Wenn du den Generator erstellt hast, kannst du sehr einfach Lizenzschlüssel automatisch generieren und versenden lassen. Dazu musst du dein Produkt bearbeiten und unter Beschreibung auf “Lizenzverwaltung” klicken. Dort kannst du das verkaufen von Lizenzschlüssel für das Produkt aktivieren und die Anzahl sowie den Generator auswählen. Den Verkauf aus dem Lager unbedingt deaktiviert lassen.

Beispiel zur Anwendung
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://classic.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://classic.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://classic.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;
        }
    }
}

Betrete unseren Discord für Updates.