If you’re developing a WordPress plugin or theme, you can easily add our license key check system. You’ll need to do a few basic steps, and we’ve included some working code from our own plugins to get you started. We also have a WP demo plugin with all the necessary files if you would like to have a look (linked below).
NOTE: Want to add BatchKeys to a WordPress theme instead? Follow these instructions.
What You’ll Need #
To check license keys you need to edit or add a few basic files to your WordPress plugin:
- main.php – we will add a little bit of code to your main plugin file
- .env file – holds your secure data, like your API auth key
- loader.php – will load the .env (or you can use any env library such as vlucas/phpdotenv)
- license-page.php – will display your key check form and hold the functions to check the key
Download Example Plugin #
If you would like to see a working example, we have created a working demo plugin that includes all the necessary files. It’s ready for you to modify into your own plugin.
Download: batchkeys-demo-plugin.zip
REMEMBER TO UPDATE THE .ENV FILE WITH YOUR ACTUAL API AUTHORIZATION CODE! You can find your API auth code in your Dashboard.
main.php #
This is your main plugin page. We assume this already exists in this example, as we only need to add a small snippet of code to the top of it.
In this example from our demo plugin that you can download from the link above above, you can see we load the mandatory files and then perform an if else statement to decide whether to show the license page only if a key has not been activated yet or the license page and the main admin page of the plugin if the key has been activated.
If you have not encoded your entire WordPress plugin, you should at least consider encoding some or all of this file.
<?php
/**
* Plugin Name: BatchKeys Demo Plugin
* Description: A demo showing how to add BatchKeys license checking to your WordPress Plugin
* Version: 1.0.0
* Author: BatchKeys
* Website: https://BatchKeys.com
*/
// Define constants, name them anything you wish
define('BATCHKEYS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('BATCHKEYS_PLUGIN_URL', plugin_dir_url(__FILE__));
// Load mandatory files
require_once(__DIR__ . '/loader.php'); // Load the loader.php which is in the same directory
load_env_variables(__DIR__ . '/.env'); // Load environment variables from the .env file in the same directory
// Load appropriate pages based on the license status --
// This will force the plugin to only show the license page until the user activates the key
// You should consider encoding this section
// https://batchkeys.com/docs/encoding-and-decoding-php/
if (!get_option('batchkeys_license')) {
require_once BATCHKEYS_PLUGIN_DIR . 'license-page.php';
} else {
require_once BATCHKEYS_PLUGIN_DIR . 'admin-page.php';
require_once BATCHKEYS_PLUGIN_DIR . 'license-page.php';
}
.env File #
Using an .env file is a standard security practicing to provide a layer of obfuscation between your sensitive developer data and the end user.
BK_API_URL=https://batchkeys.com/api.php
BK_API_AUTH=PUT_YOUR_ACTUAL_API_AUTH_KEY_FROM_YOUR_BATCHKEYS_DASHBOARD_HERE
loader.php (optional) #
For compatibility and ease of use we have created a loader to fetch the .env data. This is optional if you use a PHP .env loading library such as vlucas/phpdotenv. It’s typically best practice to use a fully functional library but the code to do this yourself can be quite simple and lightweight.
<?php
function load_env_variables($path) {
if (!file_exists($path)) {
return;
}
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) {
continue; // Skip comments
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
license-page.php #
This file will show the form for your users to input the key as well as process it with our API including the response back. We recommend encoding this file.
<?php
// This function processes the key via the BatchKeys.com API
function check_product_key($user_input) {
// Validate input format (alphanumeric with dashes)
if (!preg_match('/^[A-Za-z0-9-]+$/', $user_input)) {
return '<span class="batchkeys-error">Please enter a valid license key...</span>';
}
// Escape user input
$user_input = htmlspecialchars($user_input);
/* -- BATCHKEYS CHECK BEGIN -- */
// DO NOT EDIT THE CODE BELOW UNLESS YOU KNOW WHY YOU ARE MAKING THE CHANGES
// SEE OUR DOCUMENTATION FOR VARIOUS ADDITIONAL PARAMETERS YOU CAN SEND TO THE API
// https://batchkeys.com/docs
$apiUrl = getenv('BK_API_URL');
$authKey = getenv('BK_API_AUTH');
$domain = $_SERVER['HTTP_HOST']; // Gets the domain name of the current site, very important!
$args = array(
'method' => 'GET',
'headers' => array(
'auth' => $authKey,
'key' => $user_input,
'domain' => $domain
)
);
$response = wp_remote_request($apiUrl, $args); // Send the API request with headers
// Display message if the license key failed to check
if (is_wp_error($response)) {
return '<span class="batchkeys-error">Failed to check license key. Please try again.</span>';
}
// Handle response from API
$body = wp_remote_retrieve_body($response); // The API body response
$data = json_decode($body, true); // Parse the JSON data from the API
// See if the key is valid, save the data to the wp_options database
if ($data && isset($data['valid']) && $data['valid'] === '1') { // If the key is valid, then....
// EDIT BELOW IF YOU WOULD LIKE TO CHANGE HOW OR WHERE THE KEY DATA IS SAVED
// Set batchkeys_license to true, meaning our plugin will now function
update_option('batchkeys_license', true);
// Save the product license key
update_option('batchkeys_license_key', $user_input);
// Display a success message to the user, then reload the page after 3000 milliseconds so that the unlocked pages will now be visible
$status_message = '<span class="batchkeys-success">Success! Product key is valid. Refreshing page....</span>';
$refresh_script = '<script>setTimeout(function(){ window.location.href = "' . admin_url('admin.php?page=batchkeys-admin-page') . '"; }, 3000);</script>';
} else {
// Display a generic failure message because the key did not validate
// You can also show detailed error messages sent from the API, see our docs for instructions
$status_message = '<span class="batchkeys-error">Invalid license key. Please try again.</span>';
$refresh_script = '';
}
/* -- BATCHKEYS CHECK END -- */
return $status_message . $refresh_script;
}
// This function defines the message variables and displays the form
function batchkeys_license_page_callback() {
$status = ''; // Default status
$status_message = ''; // Default status message
$refresh_script = ''; // Default refresh script
if (isset($_POST['submit'])) {
// Validate and sanitize user input
$user_input = filter_input(INPUT_POST, 'license_key', FILTER_SANITIZE_STRING);
$status_message = check_product_key($user_input);
}
$status = get_option('batchkeys_license') ? 'License Valid' : 'No Valid License';
// Display the page
echo '
<h1>BatchKeys Demo Plugin</h1>
<div id="batchkeys-wrap">
<h3 class="batchkeys-title">License Key</h3>
<div class="batchkeys">
<h3>License Status: ' . ($status === 'License Valid' ? '<span class="batchkeys-success">' . $status . '</span>' : '<span class="batchkeys-error">' . $status . '</span>') . '</h3>
<p>Please add your license key below</p>
<form class="batchkeys-form" method="post">
<label for="license_key">License Key:</label>
<span class="batchkeys-label-spacer"> </span>
<input class="batchkeys-license-input" type="text" id="license_key" name="license_key" placeholder="Abc1234-Def5678-Ghi9012-Jkl3456-Mno7890">
<span class="batchkeys-label-spacer"> </span>
<p> ' . $status_message . ' </p>
<button class="batchkeys-button-full" type="submit" name="submit">Check License</button>
</form>
</div>
';
// Display the refresh script if called
echo $refresh_script;
echo '
</div>
';
}
Wrapping Up #
There you have it, add those files to your plugin and the user will be presented with a form to input their key before your plugin unlocks.
You’ll notice we used some css classes in the code. We provide the css in the demo plugin linked at the top of this page, or you can change them to whatever suits your design best.
To further secure your plugin we recommend additional security practices such as either using a checksum to ensure the code hasn’t been tampered with, encoding your code, or otherwise obfuscate sensitive parts of your code, or other standard security features that we couldn’t include in the demo because we wanted you to be free to modify it however you wish.