Current File : /home/pacjaorg/wpt.pacja.org/km/plugins/djclassifiedspayment/djcfpaypal/djcfpaypal.php
<?php
/**
 * @package DJ-Classifieds
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email: contact@dj-extensions.com
 */

defined('_JEXEC') or die('Restricted access');

$lang = JFactory::getLanguage();
$lang->load('plg_djclassifiedspayment_djcfpaypal',JPATH_ADMINISTRATOR);
require_once(JPATH_ROOT.'/administrator/components/com_djclassifieds/lib/djpayment.php');

class plgdjclassifiedspaymentDjcfpaypal extends JPlugin
{
	function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage('plg_djcfpaypal');

		$params["plugin_name"] = "djcfpaypal";
		$params["logo"] = "paypal.svg";
		$params["description"] = JText::_("PLG_DJCFPAYPAL_PAYMENT_METHOD_DESC");
		$params["payment_method"] = JText::_("PLG_DJCFPAYPAL_PAYMENT_METHOD_NAME");
		$params["testmode"] = $this->params->get("test");
		$params["currency_code"] = $this->params->get("currency_code");
		$params["email_id"] = $this->params->get("email_id");
		$params["image_url"] = $this->params->get("image_url");
		$params["return_ok"] = $this->params->get("return_ok",'');
		$params["return_cancel"] = $this->params->get("return_cancel",'');
		$params["payment_title"] = $this->params->get("payment_title", "[[item_name]]");

		$this->params = $params;
	}

	function onProcessPayment()
	{
		$app = JFactory::getApplication();
		$ptype = $app->input->get('ptype');
		$id = $app->input->getInt('id','0');
		$html = '';
			
		if($ptype == $this->params["plugin_name"])
		{
			$action = $app->input->get('pactiontype');
			switch ($action)
			{
				case "process" :
				$html = $this->process($id);
				break;
				case "notify" :
				$html = $this->_notify_url();
				break;
				default :
				$html = $this->process($id);
				break;
			}
		}
		return $html;
	}

	function _notify_url()
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		$account_type = $this->params["testmode"];
		$id	= $app->input->getInt('id','0');		

		$paypal_info = $app->input->post->getArray();

		$paypal_ipn = new paypal_ipn($paypal_info);
		foreach ($paypal_ipn->paypal_post_vars as $key=>$value)
		{
			if (getType($key)=="string")
			{
				eval("\$$key=\$value;");
			}
		}
		$paypal_ipn->send_response($account_type);
		if ($account_type==0 && !$paypal_ipn->is_verified())
		{
			die();
		}

		if($paypal_ipn->paypal_post_vars['txn_type'] == 'subscr_signup'){
			$this->handleRecurringInit($id, $paypal_info);
			return;
		}elseif($paypal_ipn->paypal_post_vars['txn_type'] == 'subscr_payment'){
			$this->handleRecurring($id, $paypal_info);
			return;
		}elseif($paypal_ipn->paypal_post_vars['txn_type'] == 'subscr_cancel'){
			$this->cancelRecurring($paypal_info);
			return;
		}

		$status = $paypal_ipn->get_payment_status();
		$txn_id = $paypal_ipn->paypal_post_vars['txn_id'];
		$amount = $paypal_ipn->paypal_post_vars['mc_gross'];
		if(!empty($paypal_ipn->paypal_post_vars['tax'])){
			$amount -= $paypal_ipn->paypal_post_vars['tax'];
		}
		
		if(($status=='Completed') || ($status=='Pending' && $account_type==1)){				
			DJClassifiedsPayment::completePayment($id, $amount, $txn_id);
		}else{
			$query = "UPDATE #__djcf_payments SET status='".$status."', transaction_id='".$txn_id."' WHERE id=".$id." AND method='djcfpaypal'";					
			$db->setQuery($query);
			$db->execute();	
		}
	}
	
	function process($id)
	{
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		
		$Itemid = $app->input->getInt('Itemid', '0');
		$ptype = $app->input->get('ptype');
		$type = $app->input->get('type');
		$paypal_email = $this->params["email_id"];

		$pdetails = DJClassifiedsPayment::processPayment($id, $type, $ptype);				

		if($type=='order'){
			$query ="SELECT o.* FROM #__djcf_orders o "
					."WHERE o.id=".$id." LIMIT 1";
			$db->setQuery($query);
			$order = $db->loadObject();
			
			$query ="SELECT i.*, c.price as c_price FROM #__djcf_items i "
					."LEFT JOIN #__djcf_categories c ON c.id=i.cat_id "
					."WHERE i.id=".$order->item_id." LIMIT 1";
			$db->setQuery($query);
			$item = $db->loadObject();
			
			$paypay_user = DJClassifiedsPayment::getUserPaypal($item->user_id);
			
			if($paypay_user){
				$paypal_email = $paypay_user;
			}
		}else if($type=='offer'){
			$query ="SELECT o.* FROM #__djcf_offers o "
					."WHERE o.id=".$id." LIMIT 1";
			$db->setQuery($query);
			$order = $db->loadObject();
			
			$query ="SELECT i.*, c.price as c_price FROM #__djcf_items i "
					."LEFT JOIN #__djcf_categories c ON c.id=i.cat_id "
					."WHERE i.id=".$order->item_id." LIMIT 1";
			$db->setQuery($query);
			$item = $db->loadObject();
			
			$paypay_user = DJClassifiedsPayment::getUserPaypal($item->user_id);
			
			if($paypay_user){
				$paypal_email = $paypay_user;
			}
		}

		$app->triggerEvent('onDJClassifiedsProcessDirectPayment', array($id, $type, $ptype, &$paypal_email));
		
		$urlpaypal="";
		if ($this->params["testmode"]=="1"){
			$urlpaypal="https://www.sandbox.paypal.com/cgi-bin/webscr";
		}elseif ($this->params["testmode"]=="0"){
			$urlpaypal="https://www.paypal.com/cgi-bin/webscr";
		}
		header("Content-type: text/html; charset=utf-8");
		echo JText::_('PLG_DJCFPAYPAL_REDIRECTING_PLEASE_WAIT');
		
		$return_ok = JRoute::_(JURI::root().'index.php?option=com_djclassifieds&task=paymentReturn&ptype='.$this->params["plugin_name"].'&r=ok&id='.$pdetails['item_id'].$pdetails['item_cid'].'&Itemid='.$Itemid);
		$return_cancel = JRoute::_(JURI::root().'index.php?option=com_djclassifieds&task=paymentReturn&ptype='.$this->params["plugin_name"].'&r=error&id='.$pdetails['item_id'].$pdetails['item_cid'].'&Itemid='.$Itemid);

		$btn_type = !empty($pdetails['recurring_init']) ? '_xclick-subscriptions' : '_xclick';

		$payment_title = $this->params['payment_title'];
		$payment_title = addslashes(str_replace("[[item_name]]", $pdetails['itemname'], $payment_title));
		
		$form ='<form id="paypalform" action="'.$urlpaypal.'" method="post">';
		$form .='<input type="hidden" name="cmd" value="'.$btn_type.'">';
		$form .='<input id="custom" type="hidden" name="custom" value="'.$pdetails['item_id'].'">';
		$form .='<input type="hidden" name="business" value="'.$paypal_email.'">';
		$form .='<input type="hidden" name="currency_code" value="'.strtoupper($this->params["currency_code"]).'">';
		$form .='<input type="hidden" name="item_name" value="'.$payment_title.'">';
		if(!empty($pdetails['recurring_init'])){
			$form .='<input type="hidden" name="a3" value="'.$pdetails['amount'].'">';
			$form .='<input type="hidden" name="p3" value="'.$this->getSubscrDays($id).'">';
			$form .='<input type="hidden" name="t3" value="D">';
		}else{
			$form .='<input type="hidden" name="amount" value="'.$pdetails['amount'].'">';
		}
		$form .='<input type="hidden" name="charset" value="utf-8">';		
		if($this->params["image_url"]){
			$form .='<input type="hidden" name="image_url" value="'.JURI::root().$this->params["image_url"].'">';
			$form .='<input type="hidden" name="page_style" value="paypal" />';
		}		
		$form .='<input type="hidden" name="cancel_return" value="'.$return_cancel.'">';
		$form .='<input type="hidden" name="notify_url" value="'.JURI::root().'index.php?option=com_djclassifieds&task=processPayment&ptype='.$this->params["plugin_name"].'&pactiontype=notify&id='.$pdetails['item_id'].'">';
		$form .='<input type="hidden" name="return" value="'.$return_ok.'">';
		$form .='</form>';

		$form .='<script>document.getElementById("paypalform").submit();</script>';

		echo $form;
	}

	function handleRecurringInit($pid, $paypal_info)
	{
		$db = JFactory::getDBO();

		$query = "SELECT * FROM #__djcf_payments WHERE id=".$pid;
		$db->setQuery($query);
		$payment = $db->loadObject();

		$query = "SELECT p.*  FROM #__djcf_plans p WHERE p.id='".$payment->item_id."' ";
		$db->setQuery($query);
		$plan = $db->loadObject();
		$registry = new JRegistry();
		$registry->loadString($plan->params);
		$plan_params = $registry->toObject();

		$proccessed = DJClassifiedsPayment::completePayment($pid, $paypal_info['mc_amount3']);
			
		if($proccessed){
			$query = "SELECT MAX(id) FROM #__djcf_plans_subscr WHERE plan_id=".$payment->item_id." AND user_id=".$payment->user_id." AND recurring=1";
			$db->setQuery($query);
			$subscr_id = $db->loadResult();
			if($subscr_id){
				$recurr_paypal_params = array(
					'subscr_id',
					'payer_id',
					'payer_email',
					'subscr_date',
					'period3', 
					'mc_amount3', 
					'mc_currency'
				);
				foreach($paypal_info as $key => $value){
					if(!in_array($key, $recurr_paypal_params)){
						unset($paypal_info[$key]);
					}
				}
		
				$recurr_data = array(
					'init_payment_id' => $pid,
					'last_payment_id' => $pid,
					'payment_method' => $this->params['plugin_name']
				);
		
				$recurr_data = array_merge($paypal_info, $recurr_data);

				$query = "UPDATE #__djcf_plans_subscr "
				."SET date_exp=date_start, recurr_status='Pending', recurr_data=".$db->quote(json_encode($recurr_data))." "
				."WHERE id=".$subscr_id;
				$db->setQuery($query);
				$db->execute();
			}
		}
	}

	function handleRecurring($id, $paypal_info)
	{
		if($paypal_info['payment_status'] != 'Completed'){
			return false;
		}

		$db = JFactory::getDBO();

		$query = "SELECT * FROM #__djcf_plans_subscr WHERE recurr_data LIKE '%".$this->params['plugin_name']."%' AND recurr_data LIKE '%".$paypal_info['subscr_id']."%'";
		$db->setQuery($query);
		$subscr = $db->loadObject();

		$registry = new JRegistry();
		$registry->loadString($subscr->recurr_data);
		$recurr_data = $registry->toObject();

		if($recurr_data->subscr_id != $paypal_info['subscr_id'] || $recurr_data->payer_id != $paypal_info['payer_id']){
			return false;
		}

		$registry = new JRegistry();
		$registry->loadString($subscr->plan_params);
		$plan_params = $registry->toObject();

		$recurr_data->last_payment_id = $id;

		$date_exp = new JDate($subscr->date_exp);
		$date_exp->modify('+'.$plan_params->days_limit.' day');

		$query = "UPDATE #__djcf_plans_subscr "
		."SET recurr_status='Active', date_exp = ".$db->quote($date_exp->toSQL()).", recurr_data=".$db->quote(json_encode($recurr_data))." "
		."WHERE id=".$subscr->id;
		$db->setQuery($query);
		$db->execute();

		$query = "INSERT INTO #__djcf_payments(date, item_id, user_id, method, status, ip_address, type, type_details, price) "
		."VALUES(".$db->quote(JFactory::getDate()->toSQL()).", ".$subscr->plan_id.", ".$subscr->user_id.", ".$db->quote($this->params['plugin_name']).", 'Completed', ".$db->quote($_SERVER['REMOTE_ADDR']).", 3, 'recurring',".$db->quote($recurr_data->mc_amount3).")";
		$db->setQuery($query);
		$db->execute();

		return true;
	}

	function cancelRecurring($paypal_info)
	{
		$db = JFactory::getDBO();

		$query = "SELECT * FROM #__djcf_plans_subscr WHERE recurr_data LIKE '%".$this->params['plugin_name']."%' AND recurr_data LIKE '%".$paypal_info['subscr_id']."%'";
		$db->setQuery($query);
		$subscr = $db->loadObject();

		$registry = new JRegistry();
		$registry->loadString($subscr->recurr_data);
		$recurr_data = $registry->toObject();

		if($recurr_data->subscr_id != $paypal_info['subscr_id'] || $recurr_data->payer_id != $paypal_info['payer_id']){
			return false;
		}

		$query = "UPDATE #__djcf_plans_subscr "
		."SET recurr_status='Cancelled' "
		."WHERE id=".$subscr->id;
		$db->setQuery($query);
		$db->execute();

		return true;
	}

	function getSubscrDays($id)
	{
		$db = JFactory::getDBO();
		$query = "SELECT *  FROM #__djcf_plans WHERE id='".$id."' ";
		$db->setQuery($query);
		$plan = $db->loadObject();

		$registry = new JRegistry();
		$registry->loadString($plan->params);
		$plan_params = $registry->toObject();

		return $plan_params->days_limit;
	}

	function onDJClassifiedsPaymentReturnRedirect(&$redirect)
	{
		$app = JFactory::getApplication();
		if($app->input->get('ptype') != $this->params['plugin_name']){
			return;
		}

		if($app->input->get('r') == 'ok'){
			if($this->params["return_ok"]){
				$redirect = $this->params["return_ok"];
			}
		}else{ // cancel
			if($this->params["return_cancel"]){
				$redirect = $this->params["return_cancel"];
			}
		}
	}

	function onPaymentMethodList($val)
	{
    	$type = !empty($val['type']) ? '&type='.$val['type'] : '';

		$logo_path = JURI::root()."plugins/djclassifiedspayment/".$this->params["plugin_name"]."/".$this->params["plugin_name"]."/images/".$this->params["logo"];
		$action_url = DJClassifiedsSEO::getViewUri('payment')."&layout=process&ptype=".$this->params["plugin_name"]."&id=".$val["id"].$type;

		return DJClassifiedsTheme::renderLayout('paymentmethod', 
			array(
				'name' => $this->params["payment_method"], 
				'desc' => $this->params["description"], 
				'logo_path' => $logo_path,
				'a_href' => $action_url, 
				'wrapper_attr' => 'data-recurring data-direct',
				'params' => $this->params
			)
		);
	}
}

class paypal_ipn
{
	var $paypal_post_vars;
	var $paypal_response;
	var $timeout;
	var $error_email;

	function __construct($paypal_post_vars)
	{
		$this->paypal_post_vars = $paypal_post_vars;
		$this->timeout = 120;
	}

	function send_response($account_type)
	{		
		$req = 'cmd=_notify-validate';
		if (function_exists('get_magic_quotes_gpc')) {
			$get_magic_quotes_exists = true;
		}
		//print_r($this->paypal_post_vars);
		foreach ($this->paypal_post_vars as $key => $value) {
			if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
			$value = urlencode(stripslashes($value));
			} else {
			$value = urlencode($value);
			}
			$req .= "&$key=$value";
		}
		
		// Step 2: POST IPN data back to PayPal to validate
		$ch = curl_init($account_type ? 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr' : 'https://ipnpb.paypal.com/cgi-bin/webscr');
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
		
		// In wamp-like environments that do not come bundled with root authority certificates,
		// please download 'cacert.pem' from "https://curl.haxx.se/docs/caextract.html" and set
		// the directory path of the certificate as shown below:
		// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
		
		if ( !($res = curl_exec($ch)) ) {
			//error_log("Got " . curl_error($ch) . " when processing IPN data"); 
			curl_close($ch);
			exit;
		}
		curl_close($ch);
		$this->paypal_response = $res; 
	}

	function is_verified()
	{
		if( strstr($this->paypal_response,"VERIFIED") )
			return true;
		else
			return false;
	}

	function get_payment_status()
	{
		return $this->paypal_post_vars['payment_status'];
	}
}
Site is undergoing maintenance

PACJA Events

Maintenance mode is on

Site will be available soon. Thank you for your patience!