How (not) to monetise a WordPress plugin

DO NOT DO THIS – there is some useful info in here but there are quite a few problems and you should not use it on your plugin. If you do, your WP plugin will be suspended. The issue is a WordPress T&C that states that a plugin can’t include code that is dependent on the user paying to activate it. The workaround is to create a completely separate Pro version.

In about 2010 I adopted an abandoned WordPress plugin that was really useful, but needed some TLC. I tried really hard to contact the original author but I am not sure they used their real name. So I forked their plugin to create an improved version – I could never have written it from scratch. Since then I have spent countless hours improving the plugin, the original author would hardly recognise it.

My plugin had always been free to use and I asked for donations. Between 2010 and 2022 I received less than $500 in donations for the “countless hours” I had put into the plugin. I actually didn’t have a problem with that. But then on two separate occasions, people asked for a complex feature to be added, promising a donation, and then never following through. It pissed me off and I felt they had taken advantage of me.

Rather than not keep working on the plugin (my first reaction), I decided it was time to get a reasonable return for my work. But finding information on how to monetise a WordPress plugin was pretty much impossible. There are a couple of commercial licensing solutions, but they are quite expensive.

I started with WooCommerce (WC) and the License Manager for WooCommerce plugin. WC is a no brainer, it works, is easy to set up. The License Manager also works really well, but it didn’t do some things I wanted, especially being able to get the license key in plain text to add to a database.

So after spending too much time trying to solve that, I decided to create my own API, then I could do whatever I wanted with the data. I am a hack PHP developer, I can do stuff, but I am sure that any “expert” would have a bit to say about my code. But I got this done and I hope my solution helps you.

My plugin is really useful for community and activist groups, and having run a (successful) campaign I know that usually money comes out of an individual’s pocket. So for me personally, it was important that there be a very usable free version as well as an incentive to upgrade.

I wanted a solution that

  • Worked
  • Is easy for the user to manage
  • Is easy for me to manage i.e. automated
  • Is difficult enough to circumvent – but nothing is impossible to get around
  • Is fairly priced and didn’t use a subscription model (which I regard as gouging)

Before getting into the details, here is an overview of the process, step by step.

  1. Customer purchases a license via WooCommerce
  2. If PayPal payment succeeds WC order is automatically processed
  3. A database is updated with license details
  4. License key is sent to customer in a custom email, not from WC or a license plugin


  1. Customer inserts key into a form in the plugin
  2. Data are submitted via a custom API
  3. Database is checked and updated if the key is valid
  4. API responds with the status of key
  5. Assuming valid, a cURL request is sent to update a file so that all features are enabled

I am going to assume you have a reasonable level of competency so I will skip mundane stuff e.g. setting up WC.

A few things have to happen when a customer places an order and pays. The first hurdle was that WC will leave an order as “processing” until it is manually changed to “complete”. Since I wanted this to be automated and instant, I had to find a way to have the status change on payment. The Autocomplete WooCommerce Orders plugin does exactly what it says.

To make it work you add a function to your theme-child functions.php – assuming you know at least as much PHP as me, this should be enough to go on.


function payment_complete($order_id)

// get the order and the order data
$order = wc_get_order( $order_id );
$data = $order->get_data(); 
// this is the magic
$order->update_status( 'completed' );

// generate a license key
    $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; 
    // I don't include I/L/1 and 0/O to avoid typos in some fonts = saves work for me solving this for a customer.
    $licenseKey = ""; 
    $blockLength = 4; // how many characters in a block
    $blockCount = 6; // how many blocks
    $blockDelimiter = "-";

    for($x = 0; $x < $blockCount; $x++){
        for ($i = 0; $i < $blockLength; $i++) { 
        $index = rand(0, strlen($characters) - 1); 
        $licenseKey .= $characters[$index]; 
        if( $x < ( $blockCount - 1 ) ) $licenseKey .= $blockDelimiter;
    // this produces a key something like CXK8-YHVX-G9Z6-JRWS-JF78-X2N3

// set up your PDO connection here

// save the data to the verification db
$sth = $conn->prepare("INSERT INTO licenses(licenseKey, licenseName, licenseEmail, licenseOrderID, licenseCreated) VALUES(?, ?, ?, ?, ?)");

$sth->execute(array( $licenseKey, $data['billing']['first_name'] . " " . $data['billing']['last_name'], $data['billing']['email'], $data['id'], date("Ymd-H:i:s")));

// email the key to buyer
$to = $data['billing']['email'];
$subject = 'Plugin License Key';
$from = '';

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$from."\r\n".
'Bcc:' . "\r\n" .
    'Reply-To: '.$from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
$message = '<html><body>';
$message .= "<p >Hi " .$data['billing']['first_name'] . '</p>';
$message .= '<p >Your license key is:</p>';
$message .= '<h2 >' . $licenseKey. '</h2>';
$message .= '<p >Add it at <em>dashboard</em> > <em>plugin</em> > <em>settings</em> </p>';
$message .= '</body></html>';
  // Sending email
  if(!mail($to, $subject, $message, $headers)){
    mail("", "Plugin Email Fail - functions.php", $to . " :: " .  $message);


OK, so now we have our order set to completed, we have save the data to our license database and we have sent the key to the customer. So far, so good. Now we need to handle what happens when they apply the key to upgrade to your Pro version.

On a page in the plugin I have a form to enter the key

The “click here” link goes to a page with info about the license and how to order.

When they click verify it calls some jQuery

jQuery('#licenseKeyButton').click( function () {
	var licence_key = jQuery("#license_key").val();
           type: "POST",
           url: "<?php echo admin_url('admin-ajax.php'); ?>",
           data: {action:'plugin_verify_key',key:licence_key},   
           cache: false,
           success: function(response){
                response = jQuery.parseJSON(response);
                if(response.status == "valid"){
                    //do some things e.g. change button to green
                    // do some other things e.g. change button to red      

The most important part of this is the line data: {action:'plugin_verify_key',key:licence_key}, we are using ajax to trigger a function and send the license key.

So far, so good. But before doing anything, we need to create an API. I had never done anything like this before and I was surprised that it wasn’t too complex.

I created a subdomain but you can do it any way you like, simply change URLs to suit.

The most important bit to note in the code below is "returnFile"=> "mycode" where “mycode” is part of the name of your file that is being upgraded. In this case it would be mycode.php.

To explain: When someone upgrades with their key, a cURL call is made (we’ll get to that) and the contents of a file (mycode.php) are replaced with code that doesn’t have any limitations on features. But I don’t want people to easily figure out which file that is. By passing the file name in the API response it isn’t in plain sight. But I am under no illusion that this fools everyone.

Also, there is a step for where people can revoke their key. Maybe they want to move the license to a new site. I’ll leave it to you to figure out how to grab the code from the WordPress plugin SVN to replace the Pro code with the original plugin code and do some other work. It is all based on other actions you’ll find in the code here.

// stop any casual visitors
if( !isset($_GET["key"]) ){
    echo "Thanks for visiting";

// set up your PDO connection here

// check that the key is valid
$sth = $conn->prepare("SELECT * FROM licenses WHERE theLicenseKey= :key ");
$sth->execute([':key' => $_GET["key"]]);

//get our status
if ($sth->rowCount() == 1) $status = "valid";
if ($sth->rowCount() == 0) $status = "key fail";
if ($sth->rowCount() > 1) $status = "multiple results";
if ($_GET["action"] == "revoke") $status = "revoke";

// At this point you may want to log whatever happens - I do, but you need to do some work yourself

//based on our status, if failed
if($status == "key fail"){ 
    echo "Thanks for visiting";
    mail("","API error - key fail", "Key fail for  " . $_GET["key"] . " from " . $_SERVER['REMOTE_ADDR']  );
elseif($status == "multiple results") {
// if the key exists multiple times in the database - this is incomplete so far, but is to prevent the same key being used on multiple sites
    echo "Thanks for visiting";
    mail("","API error - multiple for license", "Multiple records returned for " . $_GET["key"] . " from " . $_SERVER['REMOTE_ADDR'] );

// Update our license in the database - you remember it was added when the customer paid.  Now they are activating, we need to add that data to the record.

// first we check if they are revoking the key, if so, revert the data record
if(isset($_GET["action"]) && $_GET["action"] == "revoke" ){

    $sth3 = $conn->prepare("UPDATE licenses SET licenseActivated=0, licenseActivatedDate='', licenseDomain = "" , licenseIP='" . $_SERVER['REMOTE_ADDR'] . "' WHERE licenseKey= :key ");
    $sth3 ->execute([ ':key'=>$_GET["key"]]);
    $object = [
        "status"=> "revoked",
         "returnFile"=> "mycode"
    //send response
    header("content-type: application/json");
    // send the status and file name back
    echo json_encode($object);
// if we get this far, success.

// update the record then do more stuff
    $sth3 = $conn->prepare("UPDATE licenses SET licenseActivated=1, licenseActivatedDate='" . date("Ymd-H:i:s") . "', licenseDomain = :domain , licenseIP='" . $_SERVER['REMOTE_ADDR'] . "' WHERE licenseKey= :key");
    $sth3 ->execute([ ':domain'=>$_GET["domain"], ':key'=>$_GET["key"]]);

// create our response
while ($thekeys = $sth->fetch(PDO::FETCH_ASSOC)){
    $object = [
       "id" => $thekeys['licenseID'],
        "key"=> $thekeys['licenseKey'],
        "domain"=> $thekeys['licenseDomain'],
        "status"=> "valid",
        "returnFile"=> "mycode"

//send response
header("content-type: application/json");
echo json_encode($object);

Whew…so now we have some code waiting to receive data, test if it is valid or not and send back a response. Let’s do that.

The function to send the data is in a separate PHP script that you can name anything, so let’s call it processkey.php.

This is where our action plugin_verify_key is triggered

// you will substitute your plugin context for "plugin"
add_action('wp_ajax_plugin_verify_key', 'plugin_verify_key');
add_action('wp_ajax_nopriv_plugin_verify_key', 'plugin_verify_key');

// notice it is passing the value of "action"
function plugin_verify_key($action) {
    // check if the license key was sent, or if it already exists as an option
        $license_key_value = $_POST['key'];
        $license_key_value = get_option( 'plugin_license_key' );

    // allow for plugin upgrade, we'll get to that later
    if($action == "upgrade"){        
        $license_key_value = get_option( "plugin_license_key" );       

    //if there is no license key, stop the function
    if ($license_key_value == "" ) return; 
    $curl = curl_init();

    // set up our API call
    $url = "" . $license_key_value ."&domain=" . $the_domain . "&action=upgrade&version=" . get_option( 'plugin-version' );
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,

    // get our API response
    $response = curl_exec($curl);
        //The API returns data in JSON format, so first convert that to an array 
        $responseObj = json_decode($response, true);

    if ($responseObj["status"] == "valid"){  
            //get the name of the file from the response
            $filename = $responseObj["returnFile"] ;
            //build our URL to get the Pro version file
            $incomingURL = "" . $filename . ".txt";
            //get the contents of that file
            $getFile = file_get_contents($incomingURL);
            // where are we going to write those contents
            $thefile = dirname(__FILE__) . "/" .$filename . ".php";
            $doWrite = fopen( $thefile , "w");
            fwrite($doWrite, $getFile); 
        // obfuscate what has been done by touching each file in the directory
        $files = scandir(dirname(__FILE__));
        foreach($files as $file) {
          touch(dirname(__FILE__) . "/" .$file);

// if it is a plugin upgrade, not a new key, quit the function here
if($action == "upgrade"){ return; }

// otherwise it is a new license activation so create an array 
$response = array();

$response["status"] = $responseObj["status"];
$response["license_key"] = $responseObj["key"];
$response["licence_key_verified"] = "1";

// add some values to the wp_options table
if($response["status"] == 'valid'){
    update_option('plugin_license_key', $response["license_key"]);

// and then send our data back to the page
echo json_encode($response);

As I am creating this page, I see how complex this is. That it works is impressive…to me.

So…now they have entered their license key and clicked to verify. Assuming a valid key: the jQuery code makes an ajax call to processkey.php which sends data via cURL to Based on the result of a database lookup (Does the key exist? Only once?), the database is updated, some options are set and a file is over-written with “Pro version” code. Then a response is sent back to processkey.php which passes data back to the original page. Making sense so far? If I was reading this, I am sure at this point I would have to go back and read the code again.

Back in our form we give the user a nice response after the ajax success event. I change the colour of the button to green, the text to “verified”, disable it and hide the key with “*******”. Plus I add a message thanking people for upgrading.

The last thing to cover is if people have upgraded and I am releasing a new version of the plugin. When this happens, the entire plugin is replaced with the new version, over-writing my Pro code.

I handle this in the install function

     // whenever I do an upgrade I have to remember to change the version number here
     if ( version_compare( $installed_version, '1.0.0', '<' ) == 1 ) {
        // if it is already verified, run the function, passing the "upgrade" value
        if( get_option( 'license_key_verified' ) == 1 ){

Jump back to processkey.php and at about line 15 see if($action == "upgrade"){. This is inside a call to the plugins_loaded action and is run every time wordpress is loaded. But it checks version numbers.

Assuming it is a new version, after the plugin is updated there is the same call to re-write the file with the Pro version code but then the function stops running if($action == "upgrade"){ return; } before updating options or returning a response. So the Pro users have an upgraded plugin and still have all the features.

I am aware of a potential security issue and am working on digitally signing the files that are downloaded to upgrade to Pro.

The result of all this has been a spectacular success. I had an upgrade target for the first 2 months. Maybe I was being modest, but I have hit double that number.

Thanks for reading this far, I hope it has helped you, just like code others have shared helped me.

I wish you success with your plugin.

Leave a Reply

Your email address will not be published. Required fields are marked *