Jump to content

Licensing Integration Sample Code?


WP-MLM

Recommended Posts

I purchased the licensing add-on, great deal by the way!

 

My question is this, I have looked at the sample integration code, and would like to know if someone has a sample of how to call in the local key variable from a text file and also need to know if the local key is generated automatically by WHMCS when the first call is made to the licensing server and then would it be written to a file such as local.txt or is the local key in the file the only local key and it just needs to be pulled into the code to validate. If that is the case then the only thing that I would need to pull into the validation script would be the license key itself... which is simple enough.

 

I previously was using SPBAS, freaking hated the interface and the price was ridiculous especially compared to how much better WHMCS is! The one thing they made easy though was the integration code... I set it up in 10 minutes...

 

I've been plucking around with this code for a day now and maybe I am just having a brain fart but it would be nice to have an example:

 

1. how to integrate the local key data from a text file and then call it into the script.

2. how to write a new local key if needed to the local.txt file

 

 

 

 

Thank you for any help!

 

~Rick

Edited by WP-MLM
Link to comment
Share on other sites

Here is the code I am trying, I have sanitized it and removed a bunch of functions, I am just having issues with the logic of how to integrate it. Maybe someone can point me in the correct direction? currently when someone first installs the plugin, they can get into the WP admin to enter the license key, then because the verification is now being added they are getting locked out.

 

I was thinking that perhaps I should have a box popup for the user to enter their license key prior to the install of the plugin, then put all of the plugin files into the 'active' status else statement, but I am just not sure what the best way to do this is.

 

If I try to run all the code in the active status else statement I have no way of actually entering the license key in the first place.

 

This is a WordPress plugin, I am storing the key and the local key in the WordPress database. The local key is written to the database based on the returned results from the validator script.

 

 

<?php
defined( 'MML_ABSPATH' ) ||	define( 'MML_ABSPATH', dirname( __FILE__ )."/" );
$mlm_options = get_option("mlm_data");
$mlm_local_key = get_option("wpmlm_local_key");
// check to see if license key is set in database
if($mlm_options['wpmlm_license_key']) {
/*
*************************************************************************
*                                                                       *
* WHMCompleteSolution - Client Management, Billing & Support System     *
* Copyright (c) 2007-2010 WHMCS. All Rights Reserved,                   *
* Release Date: 1st October 2010                                        *
* Licensing Addon Integration Code                                      *
*                                                                       *
*************************************************************************
*/
// Begin Check License Function
function check_license($licensekey,$localkey="") {
### CODE REMOVED TO KEEP Unpublished for WHMCS ###
}
// End Check Function
# Get Variables from storage (retrieve from wherever it's stored - DB, file, etc...)
$licensekey = $mlm_options['wpmlm_license_key'];
$localkey = $mlm_local_key['wpmlm_local_key'];

# The call below actually performs the license check. You need to pass in the license key and the local key data
$results = check_license($licensekey,$localkey);
# For Debugging, Echo Results
echo "<textarea cols=100 rows=20>"; print_r($results); echo "</textarea>";

if ($results["status"]=="Active") {
#run script
   if ($results["localkey"]) {
       # Save Updated Local Key to DB or File
       $localkeydata = $results["localkey"];
	save_local_key($localkeydata);
   }
} elseif ($results["status"]=="Invalid") {
   # Show Invalid Message
$error_message = "Invalid WP-MLM license key, please enter a valid license key in WP-MLM Settings.";
missing_license_key_notice($error_message);
} elseif ($results["status"]=="Expired") {
   # Show Expired Message
echo "Whoops it looks like your software license has expired!";
} elseif ($results["status"]=="Suspended") {
   # Show Suspended Message
echo "Did you break a rule or something? Your license is expired!";
}
} #End if($mlm_options['wpmlm_license_key'])
###
#Start installation script
###

###
# Plus more functions...
###

###
# Action hooks
###
?>

Link to comment
Share on other sites

  • 2 weeks later...

http://docs.whmcs.com/Licensing_Addon#Integrating_the_Check_Code

 

The code used to integrate the license check is included with the addon in the file check_sample_code.php. The idea here is that you would have your user enter the license key they get issued during an install process or by simply pasting it into a file, and then you load that in your file before calling the check_license function to validate where the file is being run. For each successful check, a local key is returned which you then also store in your DB or a file to verify against locally on subsequent page loads.

Link to comment
Share on other sites

This should do the trick guys!

<?php
# The call below actually performs the license check. You need to pass in the license key and the local key data
$localkeyfile = '/var/www/license.txt';
$licensekey = 'SOMEAPP-Asd23DAASd';
$localkey = file_get_contents($localkeyfile);
$results = check_license($licensekey,$localkey);

# For Debugging, Echo Results
echo '<textarea cols=100 rows=20>'; print_r($results); echo '</textarea>';

if ($results['status']=='Active') {
   # Allow Script to Run
   if ($results['localkey']) {
       # Save Updated Local Key to DB or File
       $licensedata = $results['localkey'];
   }
} elseif ($results['status']=='Invalid') {
   # Show Invalid Message
   $licensedata = '';
} elseif ($results['status']=='Expired') {
   # Show Expired Message
   $licensedata = '';
} elseif ($results['status']=='Suspended') {
   # Show Suspended Message
   $licensedata = '';
}

file_put_contents($localkeyfile,$licensedata);
?> 

Link to comment
Share on other sites

This should do the trick guys!

Some code...

 

As a side note, the line with file_put_contents can go in the actual license check function and then you can just take the results and show an error or success message. I didn't want to post the check function here because I don't know if that can be shared publicly or not.

Link to comment
Share on other sites

<?php
# Get Settings from DB and put into variable
# Get License Key
$licensekey = get_option("license_key");
# Get WP-MLM local key
$localkey = get_option("local_key");

# The call below actually performs the license check. You need to pass in the license key and the local key data

$results = check_license($licensekey,$localkey);

# For Debugging, Echo Results
//echo '<textarea cols=100 rows=20>'; print_r($results); echo '</textarea>';

# Begin Section 
# Put this section in the function you DO NOT want to run unless active key is present
if ($results['status']=='Active') {
   # Allow Script to Run
   if ($results['localkey']) {
       # Save Updated Local Key to DB
       $localkeydata = $results["localkey"];
       save_local_key($localkeydata);
   }
} elseif ($results['status']=='Invalid') {
   # Show Invalid Message
   $licensedata = '';
} elseif ($results['status']=='Expired') {
   # Show Expired Message
   $licensedata = '';
} elseif ($results['status']=='Suspended') {
   # Show Suspended Message
   $licensedata = '';
}

}
# End of section

# Inserts local key into DB
function save_local_key($localkeydata) {
 update_option("local_key", $localkeydata);
 return;
 die;

# Inserts license key into DB
# Call this function on submission of form you use to enter license key to store in DB
function save_license_key($licensekeydata) {
 update_option("license_key", $licensekeydata);
 return;
 die;
?> 

 

I 'dumbed' this down a lot, just as an example of one method you can use, I personally used this to integrate for my WordPress plugin and it works PERFECTO!

Link to comment
Share on other sites

As a side note, the line with file_put_contents can go in the actual license check function and then you can just take the results and show an error or success message. I didn't want to post the check function here because I don't know if that can be shared publicly or not.

 

Please, post the check function. I'm going crazy trying to integrate the code because PHP it's dificult for me.

 

Thanks a million in advance.

Link to comment
Share on other sites

If Matt or a moderator says it is ok, I'll gladly post a full example!

 

I'm getting the next message in the textarea when test your code tsiedsma:

 

Array

(

[title] => 401 Authorization Required

[h1] => Authorization Required

[p] => Additionally, a 404 Not Found

error was encountered while trying to use an ErrorDocument to handle the request.

[remotecheck] => 1

)

 

Is the check function the guilty?

Link to comment
Share on other sites

It appears to be an issue with the license check function and the URL it is calling to validate the license.

 

Once again, thanks a million for your fast support tsiedsma. I'll be waitting for Matt's reply before get a refund. I feel bad, never thought I'd have to learn php to get licensing addon working.

Link to comment
Share on other sites

  • 1 month later...

Any NEws about this, i have here the same Problem, it does not Work and is not enough documented, no working Demo File only a lot of Questions...

 

) buy for this now - and there was no Text about - that it only will work, when you a coding Expert :-)

I will use it with Flat file.. And yes, we are stupid and need a step by step Documentation, not only a non Working PHP File, Thanks

 

Kasi

Link to comment
Share on other sites

<?php

$licensekey = file_get_contents('license.txt');

?>

Yes, yes nice, but

 

# Get Variables from storage (retrieve from wherever it's stored - DB, file, etc...)

$licensekey = "key";

$localkey = '9tjIxIzNwgDMwIjI6gjOztjIlRXYkt2Ylh2YioTO6M3OicmbpNnblNWasx1cyVmdyV2ccNXZsVHZv1GX

zNWbodHXlNmc192czNWbodHXzN2bkRHacBFUNFEWcNHduVWb1N2bExFd0FWTcNnclNXVcpzQioDM4ozc

7ISey9GdjVmcpRGZpxWY2JiO0EjOztjIx4CMuAjL3ITMioTO6M3OiAXaklGbhZnI6cjOztjI0N3boxWY

j9Gbuc3d3xCdz9GasF2YvxmI6MjM6M3Oi4Wah12bkRWasFmdioTMxozc7ISeshGdu9WTiozN6M3OiUGb

jl3Yn5WasxWaiJiOyEjOztjI3ATL4ATL4ADMyIiOwEjOztjIlRXYkVWdkRHel5mI6ETM6M3OicDMtcDM

tgDMwIjI6ATM6M3OiUGdhR2ZlJnI6cjOztjIlNXYlxEI5xGa052bNByUD1ESXJiO5EjOztjIl1WYuR3Y

1R2byBnI6ETM6M3OicjI6EjOztjIklGdjVHZvJHcioTO6M3Oi02bj5ycj1Ga3BEd0FWbioDNxozc7ICb

pFWblJiO1ozc7IyUD1ESXBCd0FWTioDMxozc7ISZtFmbkVmclR3cpdWZyJiO0EjOztjIlZXa0NWQiojN

6M3OiMXd0FGdzJiO2ozc7pjMxoTY8baca0885830a33725148e94e693f3f073294c0558d38e31f844

c5e399e3c16a';

 

can you tell me, where this $localkey will be written ??

I found nothing abot this in Documentation. I only will add a Example Code in php and using my License addon...!

 

What is the Problem to tell us Guys how it will work and how to install this ??

I think this Forum is for Help, not for another new Secrets :-)

 

Thanks kasi..

Link to comment
Share on other sites

  • 2 months later...

Here is the code I use for the licensing add-on. Most of it is from the example given when you buy the license add-on itself. I have also included how to test for additional add-ons for a license in the system.

 

<?php
include_once "../configs/config.inc.php";

$showcopy = 1;
// Lets get the confirguration stuff here
$dbconnect = mysql_connect($config['database']['host'], $config['database']['username'], $config['database']['password']);
mysql_select_db($config['database']['name']);

$confresults = mysql_query("SELECT * FROM ".$config['database']['tblconfig']);
while($conf = mysql_fetch_array($confresults)) {
$config['system'][$conf['option']] = stripslashes($conf['value']);
}

$licensekey = $config['system']['licensekey'];
$trialaccount = "";
if(is_file('../key/key.php')) {
include_once('../key/key.php');
}

function check_license($licensekey,$localkey="") {
   $whmcsurl = "https://www.yourdomain.com/billing/"; # This need to be wherever you have WHMCS installed.
   $licensing_secret_key = "YOURUNIQUECODEHERE"; # Set to unique value of chars
   $checkdate = date("Ymd"); # Current date
   $localkeydays = 0; # How long the local key is valid for in between remote checks
   $allowcheckfaildays = 5; # How many days to allow after local key expiry before blocking access if connection cannot be made
   $localkeyvalid = false;
   if ($localkey) {
       $localkey = str_replace("\n",'',$localkey); # Remove the line breaks
	$localdata = substr($localkey,0,strlen($localkey)-32); # Extract License Data
	$md5hash = substr($localkey,strlen($localkey)-32); # Extract MD5 Hash
       if ($md5hash==md5($localdata.$licensing_secret_key)) {
           $localdata = strrev($localdata); # Reverse the string
   		$md5hash = substr($localdata,0,32); # Extract MD5 Hash
   		$localdata = substr($localdata,32); # Extract License Data
   		$localdata = base64_decode($localdata);
   		$localkeyresults = unserialize($localdata);
           $originalcheckdate = $localkeyresults["checkdate"];
           if ($md5hash==md5($originalcheckdate.$licensing_secret_key)) {
               $localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-$localkeydays,date("Y")));
               if ($originalcheckdate>$localexpiry) {
                   $localkeyvalid = true;
                   $results = $localkeyresults;
                   $validdomains = explode(",",$results["validdomain"]);
                   if (!in_array($_SERVER['SERVER_NAME'], $validdomains)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
                   $validips = explode(",",$results["validip"]);
                   if (!in_array($_SERVER['SERVER_ADDR'], $validips)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
                   if ($results["validdirectory"]!=dirname(__FILE__)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
               }
           }
       }
   }
   if (!$localkeyvalid) {
       $postfields["licensekey"] = $licensekey;
       $postfields["domain"] = $_SERVER['SERVER_NAME'];
       $postfields["ip"] = $_SERVER['SERVER_ADDR'];
       $postfields["dir"] = dirname(__FILE__);
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($ch, CURLOPT_URL, $whmcsurl."modules/servers/licensing/verify.php");
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
       curl_setopt($ch, CURLOPT_TIMEOUT, 30);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       $data = curl_exec($ch);
       curl_close($ch);
       if (!$data) {
           $localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-($localkeydays+$allowcheckfaildays),date("Y")));
           if ($originalcheckdate>$localexpiry) {
               $results = $localkeyresults;
           } else {
               $results["status"] = "Remote Check Failed";
               return $results;
           }
       } else {
           preg_match_all('/<(.*?)>([^<]+)<\/\\1>/i', $data, $matches);
           $results = array();
           foreach ($matches[1] AS $k=>$v) {
               $results[$v] = $matches[2][$k];
           }
       }
       if ($results["status"]=="Active") {
           $results["checkdate"] = $checkdate;
           $data_encoded = serialize($results);
           $data_encoded = base64_encode($data_encoded);
           $data_encoded = md5($checkdate.$licensing_secret_key).$data_encoded;
           $data_encoded = strrev($data_encoded);
           $data_encoded = $data_encoded.md5($data_encoded.$licensing_secret_key);
           $data_encoded = wordwrap($data_encoded,80,"\n",true);
           $results["localkey"] = $data_encoded;
       }
       $results["remotecheck"] = true;
   }
   unset($postfields,$data,$matches,$whmcsurl,$licensing_secret_key,$checkdate,$localkeydays,$allowcheckfaildays,$md5hash);
   return $results;
}

// Let's create a function that locks the system out
// for trial accounts based off the trial days
function check_trial($keydate,$expdays) {
list($syear,$smon,$sday) = explode("-", $keydate);
$start = gregoriantojd($smon, $sday, $syear);
$end = gregoriantojd(date("m"),date("d"), date("Y"));	
$daysdiff = $end - $start;
$daysleft = $expdays - $daysdiff;
if($daysdiff > $expdays) {
	$expired = FALSE;
	return $expired;
}else{
	return $daysleft;
}
}

function debug_array($dataarray) {
echo "<div align='left'><pre>";
print_r($dataarray);
echo "</pre></div>";
}
function var_dump_to_string($var){
   $output = "<pre>";
   $output .= get_object_vars($var);
   $output .= "</pre>";
   return $output;
}

# The call below actually performs the license check. You need to pass in the license key and the local key data
$licresults = check_license($licensekey,$localkey);

$privatelabelactive = "";
// Lets get any add-ons the customer may have added.
$getaddons = explode('|',$licresults['addons']);

// Lets check if the client has ordered any add-ons for this license
for($s=0;$s<=count($getaddons);$s++) {
$getoptions = explode(';', $getaddons[$s]);
$chkopt = explode('=', $getoptions[0]);
if($chkopt[1] == "VIN Decoding") {
	$vdactive = explode('=', $getoptions[2]);
	$vindecodesactive = $vdactive[1];
}
if($chkopt[1] == "Vehicle Stats") {
	$statsactive = explode('=', $getoptions[2]);
	$vehiclestatsactive = $statsactive[1];
}
if($chkopt[1] == "DMS Polling") {
	$dmsactive = explode('=', $getoptions[2]);
	$dmspollingactive = $dmsactive[1];
}	
if($chkopt[1] == "Private Label") {
	$plactive = explode('=', $getoptions[2]);
	$privatelabelactive = $plactive[1];
}	
}
?>

 

That handles the licensing and will disable the system if you include it in the header of your product.

 

Then to check the add-ons you simply do this in your product:

<?php
if($vindecodesactive == "Active") {
   echo "All is good let them use it";
}eslse{
   echo "Show them an error";
}
?>

 

Hope this helps get you moving in the right direction.

Link to comment
Share on other sites

I was confused by the same thing, reading some of the prior replies reminded me of my frustration on this same thing.

 

So here is the basic flow using a flat file 'license.txt'

 

1. your software has three new files,

 

A. The license check file (you can call in whatever you want to call it) you dont have to call it what whmcs calles it, this is the file with the function in it. Just make sure you php include that file name (whatever you call it) inside the file your checking, be it index or login or whatever.

 

B. 'license.txt' - just create a text file, again call it whatever you want just change the file name in the function file above (in that section that gets that file content) to be the same name if you change it. Just create a blank txt file in the same dir as your file A above and leave it blank, but make sure you set the permissions so that the system can write to the file, i had to do 777 but you may be ok with 666 or something else. When you run the progam the function will write the information to this file, you dont have to, as log as you have the right file name in the function and also use the right filename in the file get contents command. You can remove the local key totally from your function file you dont need it in there.

 

In other words just remove this part out of the function it is just an example in this case we are getting the content from a dif flat file, just use the file get content and use your file name you made up.

 

'9tjIxIzNwgDMwIjI6gjOztjIlRXYkt2Ylh2YioTO6M3Oicmbp NnblNWasx1cyVmdyV2ccNXZsVHZv1GX

zNWbo**XlNmc192czNWbo**XzN2bkRHacBFUNFEWcNHduVWb1N 2bExFd0FWTcNnclNXVcpzQioDM4ozc

7ISey9GdjVmcpRGZpxWY2JiO0EjOztjIx4CMuAjL3ITMioTO6M 3OiAXaklGbhZnI6cjOztjI0N3boxWY

j9Gbuc3d3xCdz9GasF2YvxmI6MjM6M3Oi4Wah12bkRWasFmdio TMxozc7ISeshGdu9WTiozN6M3OiUGb

jl3Yn5WasxWaiJiOyEjOztjI3ATL4ATL4ADMyIiOwEjOztjIlR XYkVWdkRHel5mI6ETM6M3OicDMtcDM

tgDMwIjI6ATM6M3OiUG**R2ZlJnI6cjOztjIlNXYlxEI5xGa05 2bNByUD1ESXJiO5EjOztjIl1WYuR3Y

1R2byBnI6ETM6M3OicjI6EjOztjIklGdjVHZv**cioTO6M3Oi0 2bj5ycj1Ga3BEd0FWbioDNxozc7ICb

pFWblJiO1ozc7IyUD1ESXBCd0FWTioDMxozc7ISZtFmbkVmclR 3cpdWZyJiO0EjOztjIlZXa0NWQiojN

6M3OiMXd0FGdzJiO2ozc7pjMxoTY8baca0885830a33725148e 94e693f3f073294c0558d38e31f844

c5e399e3c16a';

 

these are the two commands you need to get that info.

# Get Variables from storage (retrieve from wherever it's stored - DB, file, etc...)

 

$localkeyfile = 'local_license.txt'; //if you named it that

$localkey = file_get_contents($localkeyfile);

 

and now local key has the encoded stuff you need, if it is not there the system will write it to that file. So dont feel bad it it is empty its ok, they system will take care of it.

 

 

C. now make another empty php file and call it config file of some kind, i use lic_config.php and inside that you need to put instructions inside that file for the client to copy and paste their license key. You also at some point need to modify your letter to the client in email templates to include the instructions that they should copy and paste their license key into this file (whatever you call it)

 

something like

 

/* Please replace the text (in quotes) with the license key provided to you during the order process at blahblahblaHosting.com.

* example:

* $license_key="put your key here";

*/

 

 

$licensekey="Owned-??????????";

 

//Now save the file

 

 

Important, make sure you also use the php include to include this file in your index or login whatever file your checking. So you will have three new php includes to be clear. One for the licenst txt, one for the lic config and one for the license check file with the function inside.

 

2. So now you have the files you need and the setup you need. It should work, You will need to direct the user to the appropriate page depending on the result of the query but it should work and you should be able to tweek it from there.

 

 

3. One word of caution if you find that you posted a new license in your test mode and it continues to read old data and it seems your ie page fresh or cache refresh does not work. Change the values in these two vars inside the function file. $localkeydays = ?; and $allowcheckfaildays = ?; what is prob happening is that it is not finding the new license and processing it because you have told it to wait a few days between checks with these settings. Either clear out your txt file with the encrypted code in there so it will go find a new one, or change those values, or both. I personall set mine to 1 and 1 I dont see any reason a systems should be down for longer than one day and i want it to check at least once a day regardless. So mine is 1 and 1. But its up to you.

 

 

That should clear things up. Finally i would encrypt your license check file (with the function inside it) if i were you, i just think it offers a another layer of safety. If you dont know how to encrypt it you can do so using ionCube encoder, they have an online version that you can encrypt pay as you go about 5-10 cents per page each time i think (watch it, it adds up quickly) or you can purchase the software for i think at last look it was about $200 USD I happen to have the software if you just need a few pages encrypted its no big deal ill do it for you, but i caution you im making a habbit out of redoing it over and over again for you, ill do it for free to get you set up but it is a paid service i offer so after your set up you need to decided what to do from there. I just dont want 1000 requests for free is all to do this ya know, im being nice but sometimes it bites you on a public forum like this lmao.... Its more for those that are just stuck and want to get the ball rolling.

 

Any questions ask ill pop in from time to time to see.. And yes i agree no reason they should have ever made the instructions so confusing. I also dont think its a good idea to post the check function on this forum, it makes me nervious i think we can make our point without posting the source code of the function. I hope someone removes that code. Thanks i hope i helped someone not pull their hair out over this.. lol Peace

Edited by durangod
Link to comment
Share on other sites

I also dont think its a good idea to post the check function on this forum, it makes me nervious i think we can make our point without posting the source code of the function. I hope someone removes that code. Thanks i hope i helped someone not pull their hair out over this.. lol Peace

 

Unless your running an unsecure system or you divulge your $licensing_secret_key it doesn't matter one way or the other about the check_license function being posted. For $100 you can purchase the license add-on and view that same code yourself as an example.

 

If someone with malicious intent wanted to code they would just spend the $100 and get it.

 

But for those of you whom may be insecure I will remove it or at least Matt can or another mod if they deem it necessary I cannot edit the post any longer.

Edited by Idealws
Link to comment
Share on other sites

Please help me, I'm desperate, does not work for me ...

 

 

Here is the code I use for the licensing add-on. Most of it is from the example given when you buy the license add-on itself. I have also included how to test for additional add-ons for a license in the system.

 

<?php
include_once "../configs/config.inc.php";

$showcopy = 1;
// Lets get the confirguration stuff here
$dbconnect = mysql_connect($config['database']['host'], $config['database']['username'], $config['database']['password']);
mysql_select_db($config['database']['name']);

$confresults = mysql_query("SELECT * FROM ".$config['database']['tblconfig']);
while($conf = mysql_fetch_array($confresults)) {
$config['system'][$conf['option']] = stripslashes($conf['value']);
}

$licensekey = $config['system']['licensekey'];
$trialaccount = "";
if(is_file('../key/key.php')) {
include_once('../key/key.php');
}

function check_license($licensekey,$localkey="") {
   $whmcsurl = "https://www.yourdomain.com/billing/"; # This need to be wherever you have WHMCS installed.
   $licensing_secret_key = "YOURUNIQUECODEHERE"; # Set to unique value of chars
   $checkdate = date("Ymd"); # Current date
   $localkeydays = 0; # How long the local key is valid for in between remote checks
   $allowcheckfaildays = 5; # How many days to allow after local key expiry before blocking access if connection cannot be made
   $localkeyvalid = false;
   if ($localkey) {
       $localkey = str_replace("\n",'',$localkey); # Remove the line breaks
	$localdata = substr($localkey,0,strlen($localkey)-32); # Extract License Data
	$md5hash = substr($localkey,strlen($localkey)-32); # Extract MD5 Hash
       if ($md5hash==md5($localdata.$licensing_secret_key)) {
           $localdata = strrev($localdata); # Reverse the string
   		$md5hash = substr($localdata,0,32); # Extract MD5 Hash
   		$localdata = substr($localdata,32); # Extract License Data
   		$localdata = base64_decode($localdata);
   		$localkeyresults = unserialize($localdata);
           $originalcheckdate = $localkeyresults["checkdate"];
           if ($md5hash==md5($originalcheckdate.$licensing_secret_key)) {
               $localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-$localkeydays,date("Y")));
               if ($originalcheckdate>$localexpiry) {
                   $localkeyvalid = true;
                   $results = $localkeyresults;
                   $validdomains = explode(",",$results["validdomain"]);
                   if (!in_array($_SERVER['SERVER_NAME'], $validdomains)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
                   $validips = explode(",",$results["validip"]);
                   if (!in_array($_SERVER['SERVER_ADDR'], $validips)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
                   if ($results["validdirectory"]!=dirname(__FILE__)) {
                       $localkeyvalid = false;
                       $localkeyresults["status"] = "Invalid";
                       $results = array();
                   }
               }
           }
       }
   }
   if (!$localkeyvalid) {
       $postfields["licensekey"] = $licensekey;
       $postfields["domain"] = $_SERVER['SERVER_NAME'];
       $postfields["ip"] = $_SERVER['SERVER_ADDR'];
       $postfields["dir"] = dirname(__FILE__);
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($ch, CURLOPT_URL, $whmcsurl."modules/servers/licensing/verify.php");
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
       curl_setopt($ch, CURLOPT_TIMEOUT, 30);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       $data = curl_exec($ch);
       curl_close($ch);
       if (!$data) {
           $localexpiry = date("Ymd",mktime(0,0,0,date("m"),date("d")-($localkeydays+$allowcheckfaildays),date("Y")));
           if ($originalcheckdate>$localexpiry) {
               $results = $localkeyresults;
           } else {
               $results["status"] = "Remote Check Failed";
               return $results;
           }
       } else {
           preg_match_all('/<(.*?)>([^<]+)<\/\\1>/i', $data, $matches);
           $results = array();
           foreach ($matches[1] AS $k=>$v) {
               $results[$v] = $matches[2][$k];
           }
       }
       if ($results["status"]=="Active") {
           $results["checkdate"] = $checkdate;
           $data_encoded = serialize($results);
           $data_encoded = base64_encode($data_encoded);
           $data_encoded = md5($checkdate.$licensing_secret_key).$data_encoded;
           $data_encoded = strrev($data_encoded);
           $data_encoded = $data_encoded.md5($data_encoded.$licensing_secret_key);
           $data_encoded = wordwrap($data_encoded,80,"\n",true);
           $results["localkey"] = $data_encoded;
       }
       $results["remotecheck"] = true;
   }
   unset($postfields,$data,$matches,$whmcsurl,$licensing_secret_key,$checkdate,$localkeydays,$allowcheckfaildays,$md5hash);
   return $results;
}

// Let's create a function that locks the system out
// for trial accounts based off the trial days
function check_trial($keydate,$expdays) {
list($syear,$smon,$sday) = explode("-", $keydate);
$start = gregoriantojd($smon, $sday, $syear);
$end = gregoriantojd(date("m"),date("d"), date("Y"));	
$daysdiff = $end - $start;
$daysleft = $expdays - $daysdiff;
if($daysdiff > $expdays) {
	$expired = FALSE;
	return $expired;
}else{
	return $daysleft;
}
}

function debug_array($dataarray) {
echo "<div align='left'><pre>";
print_r($dataarray);
echo "</pre></div>";
}
function var_dump_to_string($var){
   $output = "<pre>";
   $output .= get_object_vars($var);
   $output .= "</pre>";
   return $output;
}

# The call below actually performs the license check. You need to pass in the license key and the local key data
$licresults = check_license($licensekey,$localkey);

$privatelabelactive = "";
// Lets get any add-ons the customer may have added.
$getaddons = explode('|',$licresults['addons']);

// Lets check if the client has ordered any add-ons for this license
for($s=0;$s<=count($getaddons);$s++) {
$getoptions = explode(';', $getaddons[$s]);
$chkopt = explode('=', $getoptions[0]);
if($chkopt[1] == "VIN Decoding") {
	$vdactive = explode('=', $getoptions[2]);
	$vindecodesactive = $vdactive[1];
}
if($chkopt[1] == "Vehicle Stats") {
	$statsactive = explode('=', $getoptions[2]);
	$vehiclestatsactive = $statsactive[1];
}
if($chkopt[1] == "DMS Polling") {
	$dmsactive = explode('=', $getoptions[2]);
	$dmspollingactive = $dmsactive[1];
}	
if($chkopt[1] == "Private Label") {
	$plactive = explode('=', $getoptions[2]);
	$privatelabelactive = $plactive[1];
}	
}
?>

 

That handles the licensing and will disable the system if you include it in the header of your product.

 

Then to check the add-ons you simply do this in your product:

<?php
if($vindecodesactive == "Active") {
   echo "All is good let them use it";
}eslse{
   echo "Show them an error";
}
?>

 

Hope this helps get you moving in the right direction.

Link to comment
Share on other sites

@ WP-MLM

 

I have a Wordpress plugin ready to sell and want to use WHMCS to take care of the licensing / upgrades and support.

 

Can you please offer any further guidance on what you did to integrate your plugin with WHMCS licensing system?

 

How hard is it really for the client to simply remove the check file and related calls to that ?

Presumably, you'd have to ioncube ALL of your app files?

 

Any insight appreciated !

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use & Guidelines and understand your posts will initially be pre-moderated