Add WHMCS clients as affiliates to PAP via API

The following script has to be saved into the 'includes/hooks' directory of your WHMCS installation and it will be executed upon adding a new client. 
 
Make sure, that the signup page fields of Post Affiliate Pro are set to optional at Configuration > Affiliate signup > Fields (tab)

NOTE: if you wish to recognize the referring affiliate and set him as a parent of the new affiliate you must add a client custom field into the registration page and set that custom field inside WHMCS to "Show on Order Form" at Setup > Client custom fields inside the WHMCS admin panel. 
Also, you will have to use the following JS code inside /templates/default/clientregister.tpl  to write the userid of referring affiliate into that custom field:
<!--PAP integration snippet starts here-->
{literal}
<script id="pap_x2s6df8d" src="https://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript"> 
</script> 
<script type="text/javascript"> 
PostAffTracker.setAccountId('default1'); 
setTimeout(function(){PostAffTracker.writeAffiliateToCustomField('customfield3') },3000);
</script>
{/literal}
<!--PAP integration snippet ends here-->
Notice the 'customfield3' there in the code above. To find out the id of the custom field in the registration form, simply right-click the custom field in the registration form (while using Google Chrome) and select "Inspect this element". There you will see the 'id' of the field. 
E.g.:
<input type="text" name="customfield[3]" id="customfield3" value="" size="30">

WHMCS integration code (goes into /includes/hooks/ directory)
<?php
//the PapApi.class.php can be downloaded from the merchant panel: 
//Tools>Integration>API Integration

include_once 'PapApi.class.php'; //Change to correct path 
add_hook("ClientAdd",0,"pap_AddAffiliate","");

//WHMCS is supposed to post the following vars:
//userid, firstname, lastname, companyname, email, address1, address2
//city, state, postcode, country, phonenumber, password

class WHMCSPapAffiliate {	
	protected $pap_url = 'https://URL_TO_PostAffiliatePro/'; // URL to PAP
	protected $pap_user = 'merchant@username.com'; // Username
	protected $pap_password = 'demo'; // Password
	protected $logfile = '/tmp/pap.log'; // Path to log file	
	protected $debug = false;

	protected function pap_log($message){
		$log = fopen($this->logfile,'a');
		fwrite($log, date('Y-m-d H:i:s') . ':' . $message . "\n");
		fclose($log);
	}
	
	protected function isValidUserid($userid, $session) {	
		$affiliate = new Pap_Api_Affiliate($session);
		$affiliate->setUserid($userid);
		try {
		  $affiliate->load();
		  return 'Y';
		} catch (Exception $e) {
		  return;
		}
	}

	protected function isValidRefid($refid,$session) {		
		$request = new Pap_Api_AffiliatesGrid($session);		
		$request->addFilter('refid', Gpf_Data_Filter::EQUALS, $refid);		
		$request->setLimit(0, 1);
		try {
			$request->sendNow();
		} catch(Exception $e) {		  
		  return;
		}			
		$grid = $request->getGrid();
		$recordset = $grid->getRecordset();
		$totalRecords = $grid->getTotalCount();
		if ($totalRecords>0) {
			return 'Y';
		} else {
			return;
		}
	}

	public function addAffiliate($vars) {		
		$session = new Pap_Api_Session($this->pap_url . "scripts/server.php");
		if(!@$session->login($this->pap_user, $this->pap_password)) {
			if($this->debug) { 
				$this->pap_log("Cannot login. Message: ".$session->getMessage()); 
				//logActivity("pap_createAffiliate: Cannot login. Message: ".$session->getMessage());
			}
			return;
		}
		foreach ($vars as $key=>$value) {
			logActivity("pap_createAffiliate: Key: ".$key." Value: ".$value);			
		}
		//let's try to get the userid from the custom field in the signup page
		$parentuserid="";
		$whmcsuserid = $vars['userid'];
		$customfieldid = '3';//id of parentuserid  custom field we found out above
		
		$pap_query = mysql_query("SELECT value FROM tblcustomfieldsvalues WHERE (relid='$whmcsuserid' AND fieldid='$customfieldid')"); 
		$pap_query = mysql_fetch_array($pap_query);
		$useridfromCustomField = $pap_query['value'];
		
		if (($this->isValidUserid($useridfromCustomField, $session) == 'Y') || ($this->isValidRefid($useridfromCustomField, $session) == 'Y')){
			$parentuserid=$useridfromCustomField;
		} 				

		if($this->debug) {
			$this->pap_log("Adding Affiliate");
		}
					
		//Make sure that all the fields in PAP at 
        //Configuration > Affiliate signup > Fields (tab) are set to OPTIONAL
		$affiliate = new Pap_Api_Affiliate($session);
		$affiliate->setUsername($vars["email"]); 
		$affiliate->setNotificationEmail($vars["email"]); 
		$affiliate->setFirstname($vars["firstname"]); 
		$affiliate->setLastname($vars["lastname"]);
		$affiliate->setPassword($vars["password"]);
		if ($parentuserid !="") {
			$affiliate->setParentUserId($parentuserid);
		}
		$affiliate->setData(2, $vars["companyname"]);
		$affiliate->setData(3, $vars["address1"]);
		$affiliate->setData(4, $vars["city"]);
		$affiliate->setData(5, $vars["state"]);
		$affiliate->setData(6, $vars["country"]);
		$affiliate->setData(25, $vars["userid"]); //recording the WHMCS userid
		
		try {
			if ($affiliate->add()) {						
				$this->pap_log('pap_createAffiliate: Affiliate with username '.$vars["email"].' has been successfully added.');
			} else {
			  if($this->debug) { 
				$this->pap_log("Cannot save affiliate: ".$affiliate->getMessage()); 
			}
				
			}
		} catch (Exception $e) {
			if($this->debug) { 
				$this->pap_log("Error while communicating with PAP: ".$e->getMessage());				
			}
		}
		return;
	}
		
}


function pap_AddAffiliate($vars) {
	// marking the transaction as pending on PAP4
	$pap = new WHMCSPapAffiliate();
	$pap->addAffiliate($vars);
}

?>
 

That's it.
×