AAAAhome/academiac/www/plugins/vmpayment/paypal/paypal.php 0000604 00000137740 15137405460 0017212 0 ustar 00 customerData = new PaypalHelperCustomerData();
$this->_loggable = TRUE;
$this->tableFields = array_keys($this->getTableSQLFields());
$this->_tablepkey = 'id'; //virtuemart_paypal_id';
$this->_tableId = 'id'; //'virtuemart_paypal_id';
$varsToPush = array(
'paypal_merchant_email' => array('', 'char'),
'accelerated_onboarding' => array('', 'int'),
'api_login_id' => array('', 'char'),
'api_password' => array('', 'char'),
'authentication' => array('signature', 'char'),
'api_signature' => array('', 'int'),
'api_certificate' => array('', 'char'),
'sandbox' => array(0, 'int'),
'sandbox_merchant_email' => array('', 'char'),
'sandbox_api_login_id' => array('', 'char'),
'sandbox_api_password' => array('', 'char'),
'sandbox_api_signature' => array('', 'char'),
'sandbox_api_certificate' => array('', 'char'),
'sandbox_payflow_vendor' => array('', 'char'),
'sandbox_payflow_partner' => array('', 'char'),
'creditcards' => array('', 'int'),
'cvv_images' => array('', 'int'),
'paypalproduct' => array('', 'char'),
'paypal_verified_only' => array('', 'int'),
'payment_currency' => array('', 'int'),
'email_currency' => array('', 'char'),
'log_ipn' => array('', 'int'),
'payment_logos' => array('', 'char'),
'debug' => array(0, 'int'),
'log' => array(0, 'int'),
'status_pending' => array('', 'char'),
'status_success' => array('', 'char'),
'status_canceled' => array('', 'char'),
'status_expired' => array('', 'char'),
'status_capture' => array('', 'char'),
'status_refunded' => array('', 'char'),
'status_partial_refunded' => array('', 'char'),
'expected_maxamount' => array('', 'int'),
'secure_post' => array('', 'int'),
'ipn_test' => array('', 'int'),
'no_shipping' => array('', 'int'),
'address_override' => array('', 'int'),
'payment_type' => array('_xclick', 'char'),
'subcription_trials' => array(0, 'int'),
'trial1_price' => array('', 'int'),
'trial1_duration' => array('', 'char'),
//'trial2_price' => array('', 'int'),
//'trial2_duration' => array('', 'char'),
'subscription_duration' => array('', 'char'),
'subscription_term' => array('', 'int'),
'payment_plan_duration' => array('', 'char'),
'payment_plan_term' => array('', 'int'),
'payment_plan_defer' => array('', 'int'),
'payment_plan_defer_duration' => array('', 'char'),
'payment_plan_defer_strtotime' => array('', 'char'),
'billing_max_amount_type' => array('', 'char'),
'billing_max_amount' => array('', 'float'),
//Settlement
'sftp_login' => array('', 'char'),
'sftp_password' => array('', 'char'),
'sftp_host' => array('', 'char'),
'sftp_sandbox_login' => array('', 'char'),
'sftp_sandbox_password' => array('', 'char'),
//Restrictions
'countries' => array('', 'char'),
'min_amount' => array('', 'float'),
'max_amount' => array('', 'float'),
'publishup' => array('', 'char'),
'publishdown' => array('', 'char'),
//discount
'cost_per_transaction' => array('', 'float'),
'cost_percent_total' => array('', 'char'),
'tax_id' => array(0, 'int'),
//Layout
'headerBgColor' => array('', 'char'),
'headerHeight' => array('', 'char'),
'logoFont' => array('', 'char'),
'logoFontColor' => array('', 'char'),
'logoFontSize' => array('', 'char'),
'bodyBgImg' => array('', 'char'),
'bodyBgColor' => array('', 'char'),
'PageTitleTextColor' => array('', 'char'),
'PageCollapseBgColor' => array('', 'char'),
'PageCollapseTextColor' => array('', 'char'),
'orderSummaryBgColor' => array('', 'char'),
'orderSummaryBgImage' => array('', 'char'),
'footerTextColor' => array('', 'char'),
'footerTextlinkColor' => array('', 'char'),
'pageButtonBgColor' => array('', 'char'),
'pageButtonTextColor' => array('', 'char'),
'pageTitleTextColor' => array('', 'char'),
'sectionBorder' => array('', 'char'),
'bordercolor' => array('', 'char'),
'headerimg' => array('', 'char'),
'logoimg' => array('', 'char'),
'payment_action' => array('sale', 'char'),
'template' => array('', 'char'),
);
$this->setConfigParameterable($this->_configTableFieldName, $varsToPush);
//self::$_this = $this;
}
public function getVmPluginCreateTableSQL() {
return $this->createTableSQL('PayPal Table');
}
function getTableSQLFields() {
$SQLfields = array(
'id' => 'int(11) UNSIGNED NOT NULL AUTO_INCREMENT',
'virtuemart_order_id' => 'int(1) UNSIGNED',
'order_number' => 'char(64)',
'virtuemart_paymentmethod_id' => 'mediumint(1) UNSIGNED',
'payment_name' => 'varchar(5000)',
'payment_order_total' => 'decimal(15,5) NOT NULL',
'payment_currency' => 'smallint(1)',
'email_currency' => 'smallint(1)',
'cost_per_transaction' => 'decimal(10,2)',
'cost_percent_total' => 'decimal(10,2)',
'tax_id' => 'smallint(1)',
'paypal_custom' => 'varchar(255)',
'paypal_method' => 'varchar(200)',
'paypal_response_mc_gross' => 'decimal(10,2)',
'paypal_response_mc_currency' => 'char(10)',
'paypal_response_invoice' => 'char(32)',
'paypal_response_protection_eligibility' => 'char(128)',
'paypal_response_payer_id' => 'char(13)',
'paypal_response_tax' => 'decimal(10,2)',
'paypal_response_payment_date' => 'char(28)',
'paypal_response_payment_status' => 'char(50)',
'paypal_response_pending_reason' => 'char(50)',
'paypal_response_mc_fee' => 'decimal(10,2)',
'paypal_response_payer_email' => 'char(128)',
'paypal_response_last_name' => 'char(64)',
'paypal_response_first_name' => 'char(64)',
'paypal_response_business' => 'char(128)',
'paypal_response_receiver_email' => 'char(128)',
'paypal_response_transaction_subject' => 'char(128)',
'paypal_response_residence_country' => 'char(2)',
'paypal_response_txn_id' => 'char(32)',
'paypal_response_txn_type' => 'char(32)', //The kind of transaction for which the IPN message was sent
'paypal_response_parent_txn_id' => 'char(32)',
'paypal_response_case_creation_date' => 'char(32)',
'paypal_response_case_id' => 'char(32)',
'paypal_response_case_type' => 'char(32)',
'paypal_response_reason_code' => 'char(32)',
'paypalresponse_raw' => 'varchar(512)',
'paypal_fullresponse' => 'text',
);
return $SQLfields;
}
/**
* @param $product
* @param $productDisplay
* @return bool
*/
function plgVmOnProductDisplayPayment($product, &$productDisplay) {
$vendorId = 1;
if ($this->getPluginMethods($vendorId) === 0) {
return FALSE;
}
foreach ($this->methods as $this->_currentMethod) {
if ($this->_currentMethod->paypalproduct == 'exp') {
$paypalInterface = $this->_loadPayPalInterface();
$product = $paypalInterface->getExpressProduct();
$productDisplayHtml = $this->renderByLayout('expproduct',
array(
'text' => JText::_('VMPAYMENT_PAYPAL_EXPCHECKOUT_AVAILABALE'),
'img' => $product['img'],
'link' => $product['link'],
'sandbox' => $this->_currentMethod->sandbox,
'virtuemart_paymentmethod_id' => $this->_currentMethod->virtuemart_paymentmethod_id,
)
);
$productDisplay[] = $productDisplayHtml;
}
}
return TRUE;
}
function plgVmDisplayLogin(VirtuemartViewUser $user, &$html, $from_cart = FALSE) {
// only to display it in the cart, not in list orders view
if (!$from_cart) {
return NULL;
}
$vendorId = 1;
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart();
if ($this->getPluginMethods($cart->vendorId) === 0) {
return FALSE;
}
if ($cart->pricesUnformatted['salesPrice'] <= 0.0) {
return FALSE;
}
if (!($this->_currentMethod = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id))) {
return NULL;
}
$html .= $this->getExpressCheckoutHtml($this->_currentMethod, $cart);
}
function plgVmOnCheckoutAdvertise($cart, &$payment_advertise) {
if ($this->getPluginMethods($cart->vendorId) === 0) {
return FALSE;
}
if ($cart->pricesUnformatted['salesPrice'] <= 0.0) {
return NULL;
}
if (!($this->_currentMethod = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id))) {
return NULL;
}
$payment_advertise[] = $this->getExpressCheckoutHtml($this->_currentMethod, $cart);
}
function getExpressCheckoutHtml($currentMethod, $cart) {
if ($currentMethod->paypalproduct == 'exp') {
$this->_currentMethod=$currentMethod;
$paypalExpInterface = $this->_loadPayPalInterface();
$paypalExpInterface->loadCustomerData();
$expressCheckout = JRequest::getVar('expresscheckout', '');
if ($expressCheckout == 'cancel') {
$paypalExpInterface->customerData->clear();
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart();
$cart->virtuemart_paymentmethod_id = 0;
$cart->setCartIntoSession();
} else {
$paypalExpInterface->setCart($cart);
$paypalExpInterface->loadCustomerData();
$token = $paypalExpInterface->customerData->getVar('token');
$payerid = $paypalExpInterface->customerData->getVar('payer_id');
if (empty($token) and empty($payerid)) {
$paypalExpInterface->customerData->clear();
$cart->virtuemart_paymentmethod_id = 0;
$cart->setCartIntoSession();
}
if (!empty($token) and !empty($payerid)) {
return null;
}
}
}
$html = '';
foreach ($this->methods as $this->_currentMethod) {
if ($this->_currentMethod->paypalproduct == 'exp') {
$paypalInterface = $this->_loadPayPalInterface();
$button = $paypalInterface->getExpressCheckoutButton();
$html .= $this->renderByLayout('expcheckout',
array(
'text' => JText::_('VMPAYMENT_PAYPAL_EXPCHECKOUT_BUTTON'),
'img' => $button['img'],
'link' => $button['link'],
'sandbox' => $this->_currentMethod->sandbox,
'virtuemart_paymentmethod_id' => $this->_currentMethod->virtuemart_paymentmethod_id
)
);
}
}
return $html;
}
function plgVmConfirmedOrder($cart, $order) {
if (!($this->_currentMethod = $this->getVmPluginMethod($order['details']['BT']->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
return FALSE;
}
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
if (!class_exists('VirtueMartModelCurrency')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php');
}
$this->getPaymentCurrency($this->_currentMethod);
$email_currency = $this->getEmailCurrency($this->_currentMethod);
$payment_name = $this->renderPluginName($this->_currentMethod, $order);
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->debugLog('order number: ' . $order['details']['BT']->order_number, 'plgVmConfirmedOrder', 'message');
$paypalInterface->setCart($cart);
$paypalInterface->setOrder($order);
$paypalInterface->setTotal($order['details']['BT']->order_total);
$paypalInterface->loadCustomerData();
// Prepare data that should be stored in the database
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['payment_name'] = $payment_name;
$dbValues['virtuemart_paymentmethod_id'] = $cart->virtuemart_paymentmethod_id;
$dbValues['paypal_custom'] = $paypalInterface->getContext();
$dbValues['cost_per_transaction'] = $this->_currentMethod->cost_per_transaction;
$dbValues['cost_percent_total'] = $this->_currentMethod->cost_percent_total;
$dbValues['payment_currency'] = $this->_currentMethod->payment_currency;
$dbValues['email_currency'] = $email_currency;
$dbValues['payment_order_total'] = $paypalInterface->getTotal();
$dbValues['tax_id'] = $this->_currentMethod->tax_id;
$this->storePSPluginInternalData($dbValues);
VmConfig::loadJLang('com_virtuemart_orders',TRUE);
if ($this->_currentMethod->paypalproduct == 'std') {
$html = $paypalInterface->ManageCheckout();
// 2 = don't delete the cart, don't send email and don't redirect
$cart->_confirmDone = FALSE;
$cart->_dataValidated = FALSE;
$cart->setCartIntoSession();
JRequest::setVar('html', $html);
} else if ($this->_currentMethod->paypalproduct == 'exp') {
$success = $paypalInterface->ManageCheckout();
$response = $paypalInterface->getResponse();
$payment = $this->_storePaypalInternalData( $response, $order['details']['BT']->virtuemart_order_id, $cart->virtuemart_paymentmethod_id);
if ($success) {
$new_status = $paypalInterface->getNewOrderStatus();
if ($this->_currentMethod->payment_type == '_xclick-subscriptions' || $this->_currentMethod->payment_type == '_xclick-payment-plan') {
$profilesuccess = $paypalInterface->GetRecurringPaymentsProfileDetails($response['PROFILEID']);
$response = $paypalInterface->getResponse();
$this->_storePaypalInternalData( $response, $order['details']['BT']->virtuemart_order_id, $cart->virtuemart_paymentmethod_id);
}
$this->customerData->clear();
$returnValue = 1;
$html = $this->renderByLayout('expresponse',
array("method"=>$this->_currentMethod,
"success"=>$success,
"payment_name"=>$payment_name,
"response" =>$response,
"order" =>$order));
return $this->processConfirmedOrderPaymentResponse($returnValue, $cart, $order, $html, $payment_name, $new_status);
} else {
$new_status = $this->_currentMethod->status_canceled;
$returnValue = 2;
$cart->virtuemart_paymentmethod_id = 0;
$cart->setCartIntoSession();
$this->customerData->clear();
VmInfo('VMPAYMENT_PAYPAL_PAYMENT_NOT_VALID');
$paypalInterface->debugLog($response, 'plgVmConfirmedOrder, response:', 'error');
$app = JFactory::getApplication();
$app->redirect(JRoute::_('index.php?option=com_virtuemart&view=cart&Itemid=' . JRequest::getInt('Itemid'), false));
}
} else if ($this->_currentMethod->paypalproduct == 'api') {
$success = $paypalInterface->ManageCheckout();
$response = $paypalInterface->getResponse();
$payment = $this->_storePaypalInternalData( $response, $order['details']['BT']->virtuemart_order_id, $cart->virtuemart_paymentmethod_id);
if ($success) {
if ($this->_currentMethod->payment_action == 'Authorization' || $this->_currentMethod->payment_type == '_xclick-payment-plan') {
$new_status = $this->_currentMethod->status_pending;
} else {
$new_status = $this->_currentMethod->status_success;
}
if ($this->_currentMethod->payment_type == '_xclick-subscriptions' || $this->_currentMethod->payment_type == '_xclick-payment-plan') {
$profilesuccess = $paypalInterface->GetRecurringPaymentsProfileDetails($response['PROFILEID']);
$response = $paypalInterface->getResponse();
$this->_storePaypalInternalData( $response, $order['details']['BT']->virtuemart_order_id, $cart->virtuemart_paymentmethod_id);
}
$this->customerData->clear();
$returnValue = 1;
} else {
$new_status = $this->_currentMethod->status_canceled;
$returnValue = 2;
}
// $this->customerData->clear();
$html = $this->renderByLayout('apiresponse', array('method' => $this->_currentMethod, 'success' => $success, 'payment_name' => $payment_name, 'responseData' => $response, "order" => $order));
return $this->processConfirmedOrderPaymentResponse($returnValue, $cart, $order, $html, $payment_name, $new_status);
} else if ($this->_currentMethod->paypalproduct == 'hosted') {
$paypalInterface->ManageCheckout();
if ($this->_currentMethod->template == 'templateD') {
jimport('joomla.environment.browser');
$browser = JBrowser::getInstance();
// this code is only called incase of iframe (templateD), in all other cases redirecttopayapl has been done
$html = $this->renderByLayout('hostediframe', array("url" => $paypalInterface->response['EMAILLINK'],
"isMobile" => $browser->isMobile()
));
}
// 2 = don't delete the cart, don't send email and don't redirect
$cart->_confirmDone = FALSE;
$cart->_dataValidated = FALSE;
$cart->setCartIntoSession();
JRequest::setVar('html', $html);
} else {
vmError('Unknown Paypal mode');
}
}
function plgVmgetPaymentCurrency($virtuemart_paymentmethod_id, &$paymentCurrencyId) {
if (!($this->_currentMethod = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
return FALSE;
}
$this->getPaymentCurrency($this->_currentMethod);
$paymentCurrencyId = $this->_currentMethod->payment_currency;
}
function plgVmgetEmailCurrency($virtuemart_paymentmethod_id, $virtuemart_order_id, &$emailCurrencyId) {
if (!($this->_currentMethod = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
return FALSE;
}
if (!($payments = $this->_getPaypalInternalData($virtuemart_order_id))) {
// JError::raiseWarning(500, $db->getErrorMsg());
return '';
}
if (empty($payments[0]->email_currency)) {
$vendorId = 1; //VirtueMartModelVendor::getLoggedVendor();
$db = JFactory::getDBO();
$q = 'SELECT `vendor_currency` FROM `#__virtuemart_vendors` WHERE `virtuemart_vendor_id`=' . $vendorId;
$db->setQuery($q);
$emailCurrencyId = $db->loadResult();
} else {
$emailCurrencyId = $payments[0]->email_currency;
}
}
function plgVmOnPaymentResponseReceived(&$html) {
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php');
}
if (!class_exists('shopFunctionsF')) {
require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php');
}
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
VmConfig::loadJLang('com_virtuemart_orders',TRUE);
// the payment itself should send the parameter needed.
$virtuemart_paymentmethod_id = JRequest::getInt('pm', 0);
$expresscheckout = JRequest::getVar('expresscheckout', '');
if ($expresscheckout) {
return;
}
$order_number = JRequest::getString('on', 0);
$vendorId = 0;
if (!($this->_currentMethod = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
return NULL;
}
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number))) {
return NULL;
}
if (!($payments = $this->getDatasByOrderId($virtuemart_order_id))) {
return '';
}
$payment_name = $this->renderPluginName($this->_currentMethod);
$payment = end($payments);
VmConfig::loadJLang('com_virtuemart');
$orderModel = VmModel::getModel('orders');
$order = $orderModel->getOrder($virtuemart_order_id);
// to do: this
if ($payment->paypal_fullresponse) {
$paypal_data = json_decode($payment->paypal_fullresponse);
$success = ($paypal_data->payment_status == 'Completed' or $paypal_data->payment_status == 'Pending');
} else {
$success=false;
}
$html = $this->renderByLayout($this->_currentMethod->paypalproduct . 'response', array("success" => $success, "payment_name" => $payment_name, "payment" => $paypal_data, "order" => $order));
//We delete the old stuff
// get the correct cart / session
$cart = VirtueMartCart::getCart();
$cart->emptyCart();
return TRUE;
}
function plgVmOnUserPaymentCancel() {
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
$order_number = JRequest::getString('on', '');
$virtuemart_paymentmethod_id = JRequest::getInt('pm', '');
if (empty($order_number) or empty($virtuemart_paymentmethod_id) or !$this->selectedThisByMethodId($virtuemart_paymentmethod_id)) {
return NULL;
}
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number))) {
return NULL;
}
if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
return NULL;
}
VmInfo(Jtext::_('VMPAYMENT_PAYPAL_PAYMENT_CANCELLED'));
$session = JFactory::getSession();
$return_context = $session->getId();
if (strcmp($paymentTable->paypal_custom, $return_context) === 0) {
$this->handlePaymentUserCancel($virtuemart_order_id);
}
return TRUE;
}
function plgVmOnPaymentNotification() {
//https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
if (!class_exists('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
$paypal_data = JRequest::get('post');
//Recuring payment return rp_invoice_id instead of invoice
if (array_key_exists('rp_invoice_id', $paypal_data)) {
$paypal_data['invoice'] = $paypal_data['rp_invoice_id'];
}
if (!isset($paypal_data['invoice'])) {
return FALSE;
}
$order_number = $paypal_data['invoice'];
if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($paypal_data['invoice']))) {
return FALSE;
}
if (!($payments = $this->getDatasByOrderId($virtuemart_order_id))) {
return FALSE;
}
$this->_currentMethod = $this->getVmPluginMethod($payments[0]->virtuemart_paymentmethod_id);
if (!$this->selectedThisElement($this->_currentMethod->payment_element)) {
return FALSE;
}
$orderModel = VmModel::getModel('orders');
$order = $orderModel->getOrder($virtuemart_order_id);
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->setOrder($order);
$paypalInterface->debugLog($paypal_data, 'PaymentNotification, paypal_data:', 'debug');
$paypalInterface->debugLog($order_number, 'PaymentNotification, order_number:', 'debug');
$paypalInterface->debugLog($payments[0]->virtuemart_paymentmethod_id, 'PaymentNotification, virtuemart_paymentmethod_id:', 'debug');
$order_history = $paypalInterface->processIPN($paypal_data, $payments);
if (!$order_history) {
return false;
} else {
$this->_storePaypalInternalData( $paypal_data, $virtuemart_order_id, $payments[0]->virtuemart_paymentmethod_id);
$paypalInterface->debugLog('order_number:'.$order_number.' new_status:' . $order_history['order_status'], 'plgVmOnPaymentNotification', 'debug');
$orderModel->updateStatusForOneOrder($virtuemart_order_id, $order_history, TRUE);
//// remove vmcart
if (isset($paypal_data['custom'])) {
$this->emptyCart($this->_currentMethod, $paypal_data['custom'], $order_number);
}
}
}
/*********************/
/* Private functions */
/*********************/
private function _loadPayPalInterface() {
$this->_currentMethod->paypalproduct = $this->getPaypalProduct($this->_currentMethod);
if ($this->_currentMethod->paypalproduct == 'std') {
$paypalInterface = new PaypalHelperPayPalStd($this->_currentMethod,$this);
} else if ($this->_currentMethod->paypalproduct == 'api') {
$paypalInterface = new PaypalHelperPayPalApi( $this->_currentMethod,$this);
} else if ($this->_currentMethod->paypalproduct == 'exp') {
$paypalInterface = new PaypalHelperPayPalExp($this->_currentMethod, $this);
} else if ($this->_currentMethod->paypalproduct == 'hosted') {
$paypalInterface = new PaypalHelperPayPalHosted( $this->_currentMethod,$this);
} else {
Vmerror('Wrong paypal mode');
return NULL;
}
return $paypalInterface;
}
private function _storePaypalInternalData( $paypal_data, $virtuemart_order_id, $virtuemart_paymentmethod_id) {
$paypalInterface = $this->_loadPayPalInterface();
// get all know columns of the table
$db = JFactory::getDBO();
$query = 'SHOW COLUMNS FROM `' . $this->_tablename . '` ';
$db->setQuery($query);
$columns = $db->loadResultArray(0);
$post_msg = '';
/*
foreach ($paypal_data as $key => $value) {
$post_msg .= $key . "=" . $value . "
";
$table_key = 'paypal_response_' . $key;
$table_key=strtolower($table_key);
if (in_array($table_key, $columns) ) {
$response_fields[$table_key] = $value;
}
}
*/
//$response_fields = $paypalInterface->storePaypalInternalData($paypal_data);
if (array_key_exists('PAYMENTINFO_0_PAYMENTSTATUS', $paypal_data)) {
$response_fields['paypal_response_payment_status'] = $paypal_data['PAYMENTINFO_0_PAYMENTSTATUS'];
} else if (array_key_exists('PAYMENTSTATUS', $paypal_data)) {
$response_fields['paypal_response_payment_status'] = $paypal_data['PAYMENTSTATUS'];
} else if (array_key_exists('PROFILESTATUS', $paypal_data)) {
$response_fields['paypal_response_payment_status'] = $paypal_data['PROFILESTATUS'];
} else if (array_key_exists('STATUS', $paypal_data)) {
$response_fields['paypal_response_payment_status'] = $paypal_data['STATUS'];
}
if ($paypal_data) {
$response_fields['paypal_fullresponse'] = json_encode($paypal_data);
}
$response_fields['order_number'] = $paypal_data['invoice'];
$response_fields['paypal_response_invoice'] = $paypal_data['invoice'];
$response_fields['virtuemart_order_id'] = $virtuemart_order_id;
$response_fields['virtuemart_paymentmethod_id'] = $virtuemart_paymentmethod_id;
if (array_key_exists('custom', $paypal_data)) {
$response_fields['paypal_custom'] = $paypal_data['custom'];
}
//$preload=true preload the data here too preserve not updated data
return $this->storePSPluginInternalData($response_fields, $this->_tablepkey, 0);
}
private function _getPaypalInternalData($virtuemart_order_id, $order_number = '') {
$db = JFactory::getDBO();
$q = 'SELECT * FROM `' . $this->_tablename . '` WHERE ';
if ($order_number) {
$q .= " `order_number` = '" . $order_number . "'";
} else {
$q .= ' `virtuemart_order_id` = ' . $virtuemart_order_id;
}
$db->setQuery($q);
if (!($payments = $db->loadObjectList())) {
// JError::raiseWarning(500, $db->getErrorMsg());
return '';
}
return $payments;
}
protected function renderPluginName($activeMethod) {
$return = '';
$plugin_name = $this->_psType . '_name';
$plugin_desc = $this->_psType . '_desc';
$description = '';
// $params = new JParameter($plugin->$plugin_params);
// $logo = $params->get($this->_psType . '_logos');
$logosFieldName = $this->_psType . '_logos';
$logos = $activeMethod->$logosFieldName;
if (!empty($logos)) {
$return = $this->displayLogos($logos) . ' ';
}
$pluginName = $return . '' . $activeMethod->$plugin_name . '';
if ($activeMethod->sandbox ) {
$pluginName .= ' Sandbox (' . $activeMethod->virtuemart_paymentmethod_id . ')
';
}
if (!empty($activeMethod->$plugin_desc)) {
$pluginName .= '' . $activeMethod->$plugin_desc . '';
}
$pluginName .= $this->displayExtraPluginNameInfo($activeMethod);
return $pluginName;
}
function displayExtraPluginNameInfo($activeMethod) {
$this->_currentMethod=$activeMethod;
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->loadCustomerData();
$extraInfo = $paypalInterface->displayExtraPluginInfo();
return $extraInfo;
}
/**
* Display stored payment data for an order
*
* @see components/com_virtuemart/helpers/vmPSPlugin::plgVmOnShowOrderBEPayment()
*/
function plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id) {
if (!$this->selectedThisByMethodId($payment_method_id)) {
return NULL; // Another method was selected, do nothing
}
if (!($this->_currentMethod = $this->getVmPluginMethod($payment_method_id))) {
return FALSE;
}
if (!($payments = $this->_getPaypalInternalData($virtuemart_order_id))) {
// JError::raiseWarning(500, $db->getErrorMsg());
return '';
}
//$html = $this->renderByLayout('orderbepayment', array($payments, $this->_psType));
$html = '
' . "\n";
$html .= $this->getHtmlHeaderBE();
$code = "paypal_response_";
$first = TRUE;
foreach ($payments as $payment) {
$html .= '| ' . JText::_('VMPAYMENT_PAYPAL_DATE') . ' | ' . $payment->created_on . ' |
';
// Now only the first entry has this data when creating the order
if ($first) {
$html .= $this->getHtmlRowBE('COM_VIRTUEMART_PAYMENT_NAME', $payment->payment_name);
// keep that test to have it backwards compatible. Old version was deleting that column when receiving an IPN notification
if ($payment->payment_order_total and $payment->payment_order_total != 0.00) {
$html .= $this->getHtmlRowBE('COM_VIRTUEMART_TOTAL', $payment->payment_order_total . " " . shopFunctions::getCurrencyByID($payment->payment_currency, 'currency_code_3'));
}
$first = FALSE;
} else {
$paypalInterface = $this->_loadPayPalInterface();
if (isset($payment->paypal_fullresponse) and !empty($payment->paypal_fullresponse)) {
$paypal_data = json_decode($payment->paypal_fullresponse);
$paypalInterface = $this->_loadPayPalInterface();
$html .= $paypalInterface->onShowOrderBEPayment($paypal_data);
$html .= ' |
';
foreach ($paypal_data as $key => $value) {
$html .= ' ' . $key . ': ' . $value . ' ';
}
$html .= '
';
$html .= JText::_('VMPAYMENT_PAYPAL_VIEW_TRANSACTION_LOG');
$html .= ' ';
$html .= ' |
';
} else {
$html .= $paypalInterface->onShowOrderBEPaymentByFields($payment);
}
}
}
$html .= '
' . "\n";
$doc = JFactory::getDocument();
$js = "
jQuery().ready(function($) {
$('.PayPalLogOpener').click(function() {
var logId = $(this).attr('rel');
$('#PayPalLog_'+logId).toggle();
return false;
});
});";
$doc->addScriptDeclaration($js);
return $html;
}
/**
* Check if the payment conditions are fulfilled for this payment method
* @param VirtueMartCart $cart
* @param int $activeMethod
* @param array $cart_prices
* @return bool
*/
protected function checkConditions($cart, $activeMethod, $cart_prices) {
//Check method publication start
if ($activeMethod->publishup) {
$nowDate = JFactory::getDate();
$publish_up = JFactory::getDate($activeMethod->publishup);
if ($publish_up->toUnix() > $nowDate->toUnix()) {
return FALSE;
}
}
if ($activeMethod->publishdown) {
$nowDate = JFactory::getDate();
$publish_down = JFactory::getDate($activeMethod->publishdown);
if ($publish_down->toUnix() <= $nowDate->toUnix()) {
return FALSE;
}
}
$activeMethod->min_amount = (float)$activeMethod->min_amount;
$activeMethod->max_amount = (float)$activeMethod->max_amount;
$address = (($cart->ST == 0) ? $cart->BT : $cart->ST);
$amount = $this->getCartAmount($cart_prices);
$amount_cond = ($amount >= $activeMethod->min_amount AND $amount <= $activeMethod->max_amount
OR
($activeMethod->min_amount <= $amount AND ($activeMethod->max_amount == 0)));
$countries = array();
if (!empty($activeMethod->countries)) {
if (!is_array($activeMethod->countries)) {
$countries[0] = $activeMethod->countries;
} else {
$countries = $activeMethod->countries;
}
}
// probably did not gave his BT:ST address
if (!is_array($address)) {
$address = array();
$address['virtuemart_country_id'] = 0;
}
if (!isset($address['virtuemart_country_id'])) {
$address['virtuemart_country_id'] = 0;
}
if (in_array($address['virtuemart_country_id'], $countries) || count($countries) == 0) {
if ($amount_cond) {
return TRUE;
}
}
return FALSE;
}
/**
* @param $jplugin_id
* @return bool|mixed
*/
function plgVmOnStoreInstallPaymentPluginTable($jplugin_id) {
if ($jplugin_id != $this->_jid) {
return FALSE;
}
$this->_currentMethod = $this->getPluginMethod(JRequest::getInt('virtuemart_paymentmethod_id'));
if ($this->_currentMethod->published) {
$sandbox = "";
if ($this->_currentMethod->sandbox ) {
$sandbox = 'SANDBOX_';
$sandbox_param = 'sandbox_';
}
if ($this->_currentMethod->paypalproduct == 'std') {
if ($this->_currentMethod->sandbox ) {
$param = 'sandbox_merchant_email';
} else {
$param = 'paypal_merchant_email';
}
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'MERCHANT'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
}
if ($this->_currentMethod->paypalproduct == 'exp' OR $this->_currentMethod->paypalproduct == 'hosted' OR $this->_currentMethod->paypalproduct == 'api') {
$param = $sandbox_param . 'api_login_id';
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'USERNAME'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
$param = $sandbox_param . 'api_password';
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'PASSWORD'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
if ($this->_currentMethod->authentication == 'signature') {
$param = $sandbox_param . 'api_signature';
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'SIGNATURE'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
} else {
$param = $sandbox_param . 'api_certificate';
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'CERTIFICATE'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
}
}
if ($this->_currentMethod->paypalproduct == 'hosted') {
$param = $sandbox_param . 'payflow_partner';
if (empty ($this->_currentMethod->$param)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_' . $sandbox . 'PAYFLOW_PARTNER'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
}
if ($this->_currentMethod->paypalproduct == 'exp' AND empty ($this->_currentMethod->expected_maxamount)) {
$text = JText::sprintf('VMPAYMENT_PAYPAL_PARAMETER_REQUIRED', JText::_('VMPAYMENT_PAYPAL_EXPECTEDMAXAMOUNT'), $this->_currentMethod->payment_name, $this->_currentMethod->virtuemart_paymentmethod_id);
vmError($text);
}
}
return $this->onStoreInstallPluginTable($jplugin_id);
}
/**
* * This event is fired after the payment method has been selected.
* It can be used to store additional payment info in the cart.
* @param VirtueMartCart $cart
* @param $msg
* @return bool|null
*/
public function plgVmOnSelectCheckPayment(VirtueMartCart $cart, &$msg) {
if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) {
return null; // Another method was selected, do nothing
}
if (!($this->_currentMethod = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id))) {
return FALSE;
}
$paypalInterface = $this->_loadPayPalInterface($this->_currentMethod);
$paypalInterface->setCart($cart);
$paypalInterface->setTotal($cart->pricesUnformatted['billTotal']);
$paypalInterface->loadCustomerData();
$paypalInterface->getExtraPluginInfo($this->_currentMethod);
if (!$paypalInterface->validate()) {
if ($this->_currentMethod->paypalproduct != 'api') {
VmInfo('VMPAYMENT_PAYPAL_PAYMENT_NOT_VALID');
}
return false;
}
return true;
}
/*******************/
/* Order cancelled */
/* May be it is removed in VM 2.1
/*******************/
public function plgVmOnCancelPayment(&$order, $old_order_status) {
return NULL;
}
/**
* Order status changed
* @param $order
* @param $old_order_status
* @return bool|null
*/
public function plgVmOnUpdateOrderPayment(&$order, $old_order_status) {
//Load the method
if (!($this->_currentMethod = $this->getVmPluginMethod($order->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
//Load only when updating status to shipped
if ($order->order_status != $this->_currentMethod->status_capture AND $order->order_status != $this->_currentMethod->status_refunded) {
return null;
}
//Load the payments
if (!($payments = $this->_getPaypalInternalData($order->virtuemart_order_id))) {
// JError::raiseWarning(500, $db->getErrorMsg());
return null;
}
if ($this->_currentMethod->paypalproduct == 'std') {
return null;
}
//$this->_currentMethod->paypalproduct = $this->($this->_currentMethod);
$payment = end($payments);
if ($this->_currentMethod->payment_action == 'Authorization' and $order->order_status == $this->_currentMethod->status_capture) {
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->setOrder($order);
$paypalInterface->setTotal($order->order_total);
$paypalInterface->loadCustomerData();
if ($paypalInterface->DoCapture($payment)) {
$paypalInterface->debugLog(JText::_('VMPAYMENT_PAYPAL_API_TRANSACTION_CAPTURED'), 'plgVmOnUpdateOrderShipment', 'message', true);
$this->_storePaypalInternalData( $paypalInterface->getResponse(false), $order->virtuemart_order_id, $payment->virtuemart_paymentmethod_id);
}
} elseif ($order->order_status == $this->_currentMethod->status_refunded OR $order->order_status == $this->_currentMethod->status_canceled) {
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->setOrder($order);
$paypalInterface->setTotal($order->order_total);
$paypalInterface->loadCustomerData();
if ($paypalInterface->RefundTransaction($payment)) {
if ($this->_currentMethod->payment_type == '_xclick-subscriptions') {
$paypalInterface->debugLog(JText::_('VMPAYMENT_PAYPAL_SUBSCRIPTION_CANCELLED'), 'plgVmOnUpdateOrderPayment Refund', 'message', true);
} else {
//Mark the order as refunded
// $order->order_status = $method->status_refunded;
$paypalInterface->debugLog(JText::_('VMPAYMENT_PAYPAL_API_TRANSACTION_REFUNDED'), 'plgVmOnUpdateOrderPayment Refund', 'message', true);
}
$this->_storePaypalInternalData( $paypalInterface->getResponse(false), $order->virtuemart_order_id, $payment->virtuemart_paymentmethod_id);
}
}
return true;
}
function plgVmOnUpdateOrderLinePayment(&$order) {
// $xx=1;
}
/*******************/
/* Credit Card API */
/*******************/
public function _displayCVVImages($method) {
$cvv_images = $method->cvv_images;
$img = '';
if ($cvv_images) {
$img = $this->displayLogos($cvv_images);
$img = str_replace('"', "'", $img);
}
return $img;
}
/**
* * List payment methods selection
* @param VirtueMartCart $cart
* @param int $selected
* @param $htmlIn
* @return bool
*/
public function plgVmDisplayListFEPayment(VirtueMartCart $cart, $selected = 0, &$htmlIn) {
if ($this->getPluginMethods($cart->vendorId) === 0) {
if (empty($this->_name)) {
$app = JFactory::getApplication();
$app->enqueueMessage(JText::_('COM_VIRTUEMART_CART_NO_' . strtoupper($this->_psType)));
return false;
} else {
return false;
}
}
$method_name = $this->_psType . '_name';
$htmla = array();
foreach ($this->methods as $this->_currentMethod) {
if ($this->checkConditions($cart, $this->_currentMethod, $cart->pricesUnformatted)) {
$html = '';
$cart_prices = array();
$cart_prices['withTax'] = '';
$cart_prices['salesPrice'] = '';
$methodSalesPrice = $this->setCartPrices($cart, $cart_prices, $this->_currentMethod);
//if ($selected == $method->virtuemart_paymentmethod_id) {
// $this->customerData->load();
//}
$html .= '
';
$this->_currentMethod->$method_name = $this->renderPluginName($this->_currentMethod);
$html .= $this->getPluginHtml($this->_currentMethod, $selected, $methodSalesPrice);
if ($this->_currentMethod->paypalproduct == 'api') {
if (empty($this->_currentMethod->creditcards)) {
$this->_currentMethod->creditcards = PaypalHelperPaypal::getPaypalCreditCards();
} elseif (!is_array($this->_currentMethod->creditcards)) {
$this->_currentMethod->creditcards = (array)$this->_currentMethod->creditcards;
}
$html .= $this->renderByLayout('creditcardform', array('creditcards' => $this->_currentMethod->creditcards,
'virtuemart_paymentmethod_id' => $this->_currentMethod->virtuemart_paymentmethod_id,
'method' => $this->_currentMethod,
'sandbox' => $this->_currentMethod->sandbox,
'customerData' => $this->customerData));
}
if ($this->_currentMethod->payment_type == '_xclick-auto-billing' && $this->_currentMethod->billing_max_amount_type == 'cust') {
$html .= $this->renderByLayout('billingmax', array("method"=>$this->_currentMethod, "customerData"=>$this->customerData));
}
if ($this->_currentMethod->payment_type == '_xclick-subscriptions') {
$paypalInterface = $this->_loadPayPalInterface();
$html .= '
' . $paypalInterface->getRecurringProfileDesc() . '';
}
if ($this->_currentMethod->payment_type == '_xclick-payment-plan') {
$paypalInterface = $this->_loadPayPalInterface();
$html .= '
' . $paypalInterface->getPaymentPlanDesc() . '';
}
$htmla[] = $html;
}
}
$htmlIn[] = $htmla;
return true;
}
/**
* Validate payment on checkout
* @param VirtueMartCart $cart
* @return bool|null
*/
function plgVmOnCheckoutCheckDataPayment(VirtueMartCart $cart) {
if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) {
return NULL; // Another method was selected, do nothing
}
if (!($this->_currentMethod = $this->getVmPluginMethod($cart->virtuemart_paymentmethod_id))) {
return FALSE;
}
//If PayPal express, make sure we have a valid token.
//If not, redirect to PayPal to get one.
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->setCart($cart);
$cart->getCartPrices();
$paypalInterface->setTotal($cart->pricesUnformatted['billTotal']);
// Here we only check for token, but should check for payer id ?
$paypalInterface->loadCustomerData();
$paypalInterface->getExtraPluginInfo($this->_currentMethod);
if (!$paypalInterface->validate()) {
return false;
}
//Validate amount
//if ($totalInPaymentCurrency <= 0) {
// vmInfo (JText::_ ('VMPAYMENT_PAYPAL_PAYMENT_AMOUNT_INCORRECT'));
// return FALSE;
//}
}
/**
* For Express Checkout
* @param $type
* @param $name
* @param $render
* @return bool|null
*/
function plgVmOnSelfCallFE($type, $name, &$render) {
if ($name != $this->_name || $type != 'vmpayment') {
return FALSE;
}
$action = jRequest::getWord('action');
$virtuemart_paymentmethod_id = JRequest::getInt('virtuemart_paymentmethod_id');
//Load the method
if (!($this->_currentMethod = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if ($action != 'SetExpressCheckout') {
return false;
}
if (!class_exists('VirtueMartCart')) {
require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart();
$cart->virtuemart_paymentmethod_id = $virtuemart_paymentmethod_id;
$cart->setCartIntoSession();
$paypalInterface = $this->_loadPayPalInterface();
$paypalInterface->setCart($cart);
$paypalInterface->setTotal($cart->pricesUnformatted['billTotal']);
$paypalInterface->loadCustomerData();
$paypalInterface->getExtraPluginInfo($this->_currentMethod);
if (!$paypalInterface->validate()) {
VmInfo('VMPAYMENT_PAYPAL_PAYMENT_NOT_VALID');
return false;
} else {
$app = JFactory::getApplication();
$app->redirect(JRoute::_('index.php?option=com_virtuemart&view=cart&Itemid=' . JRequest::getInt('Itemid'), false));
}
}
//Calculate the price (value, tax_id) of the selected method, It is called by the calculator
//This function does NOT to be reimplemented. If not reimplemented, then the default values from this function are taken.
public function plgVmOnSelectedCalculatePricePayment(VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) {
return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name);
}
/* backward compatibility */
function getPaypalProduct(){
if (isset($this->_currentMethod->paypalproduct) and !empty($this->_currentMethod->paypalproduct)) {
return $this->_currentMethod->paypalproduct;
} else {
return 'std';
}
}
// Checks how many plugins are available. If only one, the user will not have the choice. Enter edit_xxx page
// The plugin must check first if it is the correct type
function plgVmOnCheckAutomaticSelectedPayment(VirtueMartCart $cart, array $cart_prices = array(), &$paymentCounter) {
return $this->onCheckAutomaticSelected($cart, $cart_prices, $paymentCounter);
}
// This method is fired when showing the order details in the frontend.
// It displays the method-specific data.
public function plgVmOnShowOrderFEPayment($virtuemart_order_id, $virtuemart_paymentmethod_id, &$payment_name) {
$this->onShowOrderFE($virtuemart_order_id, $virtuemart_paymentmethod_id, $payment_name);
}
// This method is fired when showing when priting an Order
// It displays the the payment method-specific data.
function plgVmonShowOrderPrintPayment($order_number, $method_id) {
return $this->onShowOrderPrint($order_number, $method_id);
}
function plgVmDeclarePluginParamsPayment($name, $id, &$data) {
return $this->declarePluginParams('payment', $name, $id, $data);
}
function plgVmSetOnTablePluginParamsPayment($name, $id, &$table) {
return $this->setOnTablePluginParams($name, $id, $table);
}
}
// No closing tag
home/academiac/www/plugins/vmpayment/paypal/paypal/helpers/paypal.php 0000604 00000076676 15137411027 0022150 0 ustar 00 context = $session->getId();
$this->_method = $method;
$this->paypalPlugin = $paypalPlugin;
//Set the vendor
$vendorModel = VmModel::getModel('Vendor');
$vendorModel->setId($this->_method->virtuemart_vendor_id);
$vendor = $vendorModel->getVendor();
$vendorModel->addImages($vendor, 1);
$this->vendor = $vendor;
$this->getPaypalPaymentCurrency();
}
function getPaypalPaymentCurrency($getCurrency = FALSE) {
vmPSPlugin::getPaymentCurrency($this->_method);
$this->currency_code_3 = shopFunctions::getCurrencyByID($this->_method->payment_currency, 'currency_code_3');
}
public function getContext() {
return $this->context;
}
public function setCart($cart) {
$this->cart = $cart;
if (!isset($this->cart->pricesUnformatted)) {
$this->cart->getCartPrices();
}
}
public function setOrder($order) {
$this->order = $order;
}
public function setCustomerData($customerData) {
$this->customerData = $customerData;
}
public function loadCustomerData() {
$this->customerData = new PaypalHelperCustomerData();
$this->customerData->load();
$this->customerData->loadPost();
}
function getItemName($name) {
return substr(strip_tags($name), 0, 127);
}
function getProductAmount($productPricesUnformatted) {
if ($productPricesUnformatted['salesPriceWithDiscount']) {
return vmPSPlugin::getAmountValueInCurrency($productPricesUnformatted['salesPriceWithDiscount'], $this->_method->payment_currency);
} else {
return vmPSPlugin::getAmountValueInCurrency($productPricesUnformatted['salesPrice'], $this->_method->payment_currency);
}
}
function addRulesBill($rules) {
$handling = 0;
foreach ($rules as $rule) {
$handling += vmPSPlugin::getAmountValueInCurrency($this->cart->pricesUnformatted[$rule['virtuemart_calc_id'] . 'Diff'], $this->_method->payment_currency);
}
return $handling;
}
/**
* @return value
*/
function getHandlingAmount() {
$handling = 0;
$handling += $this->addRulesBill($this->cart->cartData['DBTaxRulesBill']);
$handling += $this->addRulesBill($this->cart->cartData['taxRulesBill']);
$handling += $this->addRulesBill($this->cart->cartData['DATaxRulesBill']);
$handling += vmPSPlugin::getAmountValueInCurrency($this->cart->pricesUnformatted['salesPricePayment'], $this->_method->payment_currency);
return $handling;
}
public function setTotal($total) {
if (!class_exists('CurrencyDisplay')) {
require(JPATH_VM_ADMINISTRATOR . '/helpers/currencydisplay.php');
}
$this->total = vmPSPlugin::getAmountValueInCurrency($total, $this->_method->payment_currency);
$cd = CurrencyDisplay::getInstance($this->cart->pricesCurrency);
}
public function getTotal() {
return $this->total;
}
public function getResponse() {
return $this->response;
}
public function getRequest() {
$this->debugLog($this->requestData, 'PayPal ' . $this->requestData['METHOD'] . ' Request variables ', 'debug');
return $this->requestData;
}
protected function sendRequest($post_data) {
$retryCodes = array('401', '403', '404',);
$this->post_data = $post_data;
$post_url = $this->_getApiUrl();
$post_string = $this->ToUri($post_data);
$curl_request = curl_init($post_url);
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl_request, CURLOPT_HEADER, 0);
curl_setopt($curl_request, CURLOPT_TIMEOUT, $this->_timeout);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
if ($this->_method->authentication == 'certificate') {
$certPath = "";
$passPhrase = "";
$this->getSSLCertificate($certPath, $passPhrase);
curl_setopt($curl_request, CURLOPT_SSLCERT, $certPath);
curl_setopt($curl_request, CURLOPT_SSLCERTPASSWD, $passPhrase);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYHOST, 2);
} else {
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($curl_request, CURLOPT_POST, 1);
if (preg_match('/xml/', $post_url)) {
curl_setopt($curl_request, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
}
$response = curl_exec($curl_request);
if ($curl_error = curl_error($curl_request)) {
$this->debugLog($curl_error, '----CURL ERROR----', 'error');
}
/*
$httpStatus = curl_getinfo($curl_request, CURLINFO_HTTP_CODE);
$retries = 0;
if(in_array($httpStatus, $retryCodes) && isset($this->retry)) {
$this->debugLog("Got $httpStatus response from server. Retrying");
do {
$result = curl_exec(debugLog);
$httpStatus = curl_getinfo(debugLog, CURLINFO_HTTP_CODE);
} while (in_array($httpStatus, self::$retryCodes) && ++$retries < $this->retry );
}
*/
$responseArray = array();
parse_str($response, $responseArray); // Break the NVP string to an array
curl_close($curl_request);
//$responseArray['invoice'] = $this->order['details']['BT']->order_number;
$responseArray['custom'] = $this->context;
$responseArray['method'] = $post_data['METHOD'];
$this->response = $responseArray;
if ($this->response['ACK'] == 'SuccessWithWarning') {
$level = 'warning';
} else {
$level = 'debug';
}
$this->debugLog($post_data, 'PayPal ' . $post_data['METHOD'] . ' Request variables:', $level);
$this->debugLog($this->response, 'PayPal response:', $level);
return $this->response;
}
/**
* Get ssl parameters for certificate based client authentication
*
* @param string $certPath - path to client certificate file (PEM formatted file)
*/
public function getSSLCertificate(&$certifPath, &$passPhrase) {
$safePath = VmConfig::get('forSale_path', '');
if ($safePath) {
$sslCertifFolder = $safePath . "paypal";
}
$certifPath = $sslCertifFolder . DS . $this->api_certificate;
}
protected function setTimeOut($value = 45) {
$this->_timeout = $value;
}
protected function _getPayPalUrl($protocol = 'https://', $includePath = true) {
$url = ($this->_method->sandbox ) ? $protocol . 'www.sandbox.paypal.com' : $protocol . 'www.paypal.com';
if ($includePath) {
$url .= '/cgi-bin/webscr';
}
return $url;
}
protected function _getApiUrl() {
$url_auth = "";
if ($this->_method->authentication == 'signature') {
$url_auth = "-3t";
}
$url_environment = "";
if ($this->_method->sandbox ) {
$url_environment = ".sandbox";
}
//return ($this->_method->sandbox=='sandbox') ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp';
return 'https://api' . $url_auth . $url_environment . '.paypal.com/nvp';
}
protected function getDurationValue($duration) {
$parts = explode('-', $duration);
return $parts[0];
}
protected function getDurationUnit($duration) {
$parts = explode('-', $duration);
return $parts[1];
}
protected function truncate($string, $length) {
return substr($string, 0, $length);
}
protected function _getFormattedDate($month, $year) {
return sprintf('%02d%04d', $month, $year);
}
public function validate($enqueueMessage = true) {
return true;
}
public function validatecheckout($enqueueMessage = true) {
return true;
}
function ToUri($post_variables) {
$poststring = '';
foreach ($post_variables AS $key => $val) {
$poststring .= urlencode($key) . "=" . urlencode($val) . "&";
}
$poststring = rtrim($poststring, "& ");
return $poststring;
}
public function displayExtraPluginInfo() {
$extraInfo = '';
if ($this->_method->payment_type == '_xclick-auto-billing' && $this->customerData->getVar('autobilling_max_amount')) {
$cd = CurrencyDisplay::getInstance($this->_method->payment_currency);
$extraInfo .= '
';
$extraInfo .= JText::_('VMPAYMENT_PAYPAL_PAYMENT_BILLING_MAX_AMOUNT') . ': ' . $cd->priceDisplay($this->customerData->getVar('autobilling_max_amount'));
}
if ($this->_method->payment_type == '_xclick-subscriptions') {
$extraInfo .= '
';
$extraInfo .= $this->getRecurringProfileDesc();
$extraInfo .= '';
}
if ($this->_method->payment_type == '_xclick-payment-plan') {
$extraInfo .= '
';
$extraInfo .= $this->getPaymentPlanDesc();
$extraInfo .= '';
}
return $extraInfo;
}
public function getExtraPluginInfo() {
$extraInfo = '';
return $extraInfo;
}
public function getLogoImage() {
if ($this->_method->logoimg) {
return JURI::base() . '/images/stories/virtuemart/payment/' . $this->_method->logoimg;
} else {
return JURI::base() . $this->vendor->images[0]->file_url;
}
}
public function getRecurringProfileDesc() {
// $recurringDesc = '';
// if ($this->_method->subcription_trials) {
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_TRIAL_PERIODS') . $this->_method->trial1_duration . ': '.$this->_method->trial1_price.'
';
// }
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_SUBSCRIPTION_DURATION').': '.$this->_method->subscription_duration . '
';
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_SUBSCRIPTION_TERM').': '.$this->_method->subscription_term . '
';
$durationValue = $this->getDurationValue($this->_method->subscription_duration);
$durationUnit = $this->getDurationUnit($this->_method->subscription_duration);
$recurringDesc = JText::sprintf('VMPAYMENT_PAYPAL_SUBSCRIPTION_DESCRIPTION', $durationValue, $durationUnit, $this->_method->subscription_term);
return $recurringDesc;
}
public function getPaymentPlanDesc() {
// $recurringDesc = '';
// if ($this->_method->subcription_trials) {
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_TRIAL_PERIODS') . $this->_method->trial1_duration . ': '.$this->_method->trial1_price.'
';
// }
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_SUBSCRIPTION_DURATION').': '.$this->_method->subscription_duration . '
';
// $recurringDesc .= JText::_('VMPAYMENT_PAYPAL_SUBSCRIPTION_TERM').': '.$this->_method->subscription_term . '
';
$durationValue = $this->getDurationValue($this->_method->payment_plan_duration);
$durationUnit = $this->getDurationUnit($this->_method->payment_plan_duration);
$recurringDesc = JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_PLAN_DESCRIPTION', $this->_method->payment_plan_term, $durationValue, $durationUnit);
if ($this->_method->payment_plan_defer && $this->_method->paypalproduct == 'std') {
$defer_duration = $this->getDurationValue($this->_method->payment_plan_defer_duration);
$defer_unit = $this->getDurationUnit($this->_method->payment_plan_defer_duration);
$startDate = JFactory::getDate('+' . $defer_duration . ' ' . $defer_unit);
$recurringDesc .= '
' . JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_PLAN_INITIAL_PAYMENT', JHTML::_('date', $startDate->toFormat(), JText::_('DATE_FORMAT_LC4')));
} else if ($this->_method->payment_plan_defer_strtotime) {
$startDate = JFactory::getDate($this->_method->payment_plan_defer_strtotime);
$recurringDesc .= '
' . JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_PLAN_INITIAL_PAYMENT', JHTML::_('date', $startDate->toFormat(), JText::_('DATE_FORMAT_LC4')));
//$recurringDesc .= '
'.JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_PLAN_INITIAL_PAYMENT',date(JText::_('DATE_FORMAT_LC4'),strtotime('first day of next month')));
}
return $recurringDesc;
}
/********************************/
/* Instant Payment Notification */
/********************************/
public function processIPN($paypal_data, $payments) {
// check that the remote IP is from Paypal.
if (!$this->checkPaypalIps($paypal_data)) {
return false;
}
// Validate the IPN content upon PayPal
if (!$this->validateIpnContent($paypal_data)) {
return false;
}
//Check the PayPal response
/*
* https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables
* The status of the payment:
* Canceled_Reversal: A reversal has been canceled. For example, you won a dispute with the customer, and the funds for the transaction that was reversed have been returned to you.
* Completed: The payment has been completed, and the funds have been added successfully to your account balance.
* Created: A German ELV payment is made using Express Checkout.
* Denied: You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the pending_reason variable or the Fraud_Management_Filters_x variable.
* Expired: This authorization has expired and cannot be captured.
* Failed: The payment has failed. This happens only if the payment was made from your customer’s bank account.
* Pending: The payment is pending. See pending_reason for more information.
* Refunded: You refunded the payment.
* Reversed: A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element.
* Processed: A payment has been accepted.
* Voided: This authorization has been voided.
*/
$order_history = array();
$order_history['customer_notified'] = 1;
if ($paypal_data['txn_type'] == 'subscr_cancel') {
$order_history['order_status'] = $this->_method->status_canceled;
} elseif ($paypal_data['txn_type'] == 'mp_cancel') {
$order_history['order_status'] = $this->_method->status_canceled;
} elseif ($paypal_data['txn_type'] == 'subscr_eot') {
$order_history['order_status'] = $this->_method->status_expired;
} elseif ($paypal_data['txn_type'] == 'recurring_payment_expired') {
$order_history['order_status'] = $this->_method->status_expired;
} elseif ($paypal_data['txn_type'] == 'subscr_signup') {
//TODO: Validate the response
$order_history['order_status'] = $this->_method->status_success;
} elseif ($paypal_data['txn_type'] == 'recurring_payment_profile_created') {
if ($paypal_data['profile_status'] == 'Active') {
$order_history['order_status'] = $this->_method->status_success;
} else {
$order_history['order_status'] = $this->_method->status_canceled;
}
} else if (strcmp($paypal_data['payment_status'], 'Completed') == 0) {
$this->debugLog('Completed', 'payment_status', 'debug');
// 1. check the payment_status is Completed
// 2. check that txn_id has not been previously processed
if ($this->_check_txn_id_already_processed($payments, $paypal_data['txn_id'])) {
$this->debugLog($paypal_data['txn_id'], '_check_txn_id_already_processed', 'debug');
return FALSE;
}
// 3. check email and amount currency is correct
if ($paypal_data['txn_type'] != 'recurring_payment' && !$this->_check_email_amount_currency($payments, $paypal_data)) {
return FALSE;
}
// now we can process the payment
if (strcmp($paypal_data['payment_status'], 'Authorization') == 0) {
$order_history['order_status'] = $this->_method->status_pending;
} else {
$order_history['order_status'] = $this->_method->status_success;
}
$order_history['comments'] = JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_STATUS_CONFIRMED', $this->order['details']['BT']->order_number);
} elseif (strcmp($paypal_data['payment_status'], 'Pending') == 0) {
$lang = JFactory::getLanguage();
$key = 'VMPAYMENT_PAYPAL_PENDING_REASON_FE_' . strtoupper($paypal_data['pending_reason']);
if (!$lang->hasKey($key)) {
$key = 'VMPAYMENT_PAYPAL_PENDING_REASON_FE_DEFAULT';
}
$order_history['comments'] = JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_STATUS_PENDING', $this->order['details']['BT']->order_number) . JText::_($key);
$order_history['order_status'] = $this->_method->status_pending;
} elseif (strcmp($paypal_data['payment_status'], 'Refunded') == 0) {
if ($this->_is_full_refund($payments, $paypal_data)) {
$order_history['comments'] = JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_STATUS_REFUNDED', $this->order['details']['BT']->order_number);
$order_history['order_status'] = $this->_method->status_refunded;
} else {
$order_history['comments'] = JText::sprintf('VMPAYMENT_PAYPAL_PAYMENT_STATUS_PARTIAL_REFUNDED', $this->order['details']['BT']->order_number);
$order_history['order_status'] = isset($this->_method->status_partial_refunded) ? $this->_method->status_partial_refunded : 'R';
}
} elseif (isset ($paypal_data['payment_status'])) {
// voided
$order_history['order_status'] = $this->_method->status_canceled;
} else {
/*
* a notification was received that concerns one of the payment (since $paypal_data['invoice'] is found in our table),
* but the IPN notification has no $paypal_data['payment_status']
* We just log the info in the order, and do not change the status, do not notify the customer
*/
$order_history['comments'] = JText::_('VMPAYMENT_PAYPAL_IPN_NOTIFICATION_RECEIVED');
$order_history['customer_notified'] = 0;
}
return $order_history;
}
protected function checkPaypalIps($paypal_data) {
/*
$test_ipn = (array_key_exists('test_ipn', $paypal_data)) ? $paypal_data['test_ipn'] : 0;
if ($test_ipn == 1) {
return true;
}
*/
$order_number = $paypal_data['invoice'];
// Get the list of IP addresses for www.paypal.com and notify.paypal.com
if ($this->_method->sandbox ) {
$paypal_iplist = gethostbynamel('ipn.sandbox.paypal.com');
$paypal_iplist = (array)$paypal_iplist;
$this->debugLog($paypal_iplist, 'checkPaypalIps SANDBOX', 'debug', false);
} else {
$paypal_iplist1 = gethostbynamel('www.paypal.com');
$paypal_iplist2 = gethostbynamel('notify.paypal.com');
$paypal_iplist3 = array('216.113.188.202', '216.113.188.203', '216.113.188.204', '66.211.170.66');
$paypal_iplist = array_merge($paypal_iplist1, $paypal_iplist2, $paypal_iplist3);
// http://forum.virtuemart.net/index.php?topic=115375.msg406664#msg406664
$paypal_iplist3 = array('216.113.188.202', '216.113.188.203', '216.113.188.204', '66.211.170.66');
// Added JH 2013-10-12
//Current IP addresses
//------------api.paypal.com---------
$paypal_iplist_api = array('173.0.88.66', '173.0.88.98', '173.0.84.66', '173.0.84.98',
'173.0.80.00', '173.0.80.01', '173.0.80.02', '173.0.80.03', '173.0.80.04', '173.0.80.05', '173.0.80.06', '173.0.80.07', '173.0.80.08', '173.0.80.09', '173.0.80.10', '173.0.80.11', '173.0.80.12', '173.0.80.13', '173.0.80.14', '173.0.80.15', '173.0.80.16', '173.0.80.17', '173.0.80.18', '173.0.80.19', '173.0.80.20');
//------------api-aa.paypal.com------------
$paypal_iplist_api_aa = array('173.0.88.67', '173.0.88.99', '173.0.84.99', '173.0.84.67');
//'------------api-3t.paypal.com------------'
$paypal_iplist_api_3t_aa = array('173.0.88.69', '173.0.88.101', '173.0.84.69', '173.0.84.101');
//------------api-aa-3t.paypal.com------------
$paypal_iplist_api_aa_3t = array('173.0.88.68', '173.0.88.100', '173.0.84.68', '173.0.84.100');
//------------notify.paypal.com (IPN delivery)------------
$paypal_iplist_notify = array('173.0.81.1', '173.0.81.33');
//'-----------reports.paypal.com-----------'
$paypal_iplist_reports = array('66.211.168.93', '173.0.84.161', '173.0.84.198', '173.0.88.161', '173.0.88.198');
//'------------www.paypal.com------------'
//'Starting September 12, 2012 www.paypal.com will start resolving to a dynamic list of IP addresses and as such should not be whitelisted.'
//'For more information on IPNs please go here.'
//'------------ipnpb.paypal.com------------'
$paypal_iplist_ipnb = array('64.4.240.0', '64.4.240.1', '64.4.240.2', '64.4.240.3', '64.4.240.4', '64.4.240.5', '64.4.240.6', '64.4.240.7', '64.4.240.8', '64.4.240.9', '64.4.240.10', '64.4.240.11', '64.4.240.12', '64.4.240.13', '64.4.240.14', '64.4.240.15', '64.4.240.16', '64.4.240.17', '64.4.240.18', '64.4.240.19', '64.4.240.20',
'118.214.15.186', '118.215.103.186', '118.215.119.186', '118.215.127.186', '118.215.15.186', '118.215.151.186', '118.215.159.186', '118.215.167.186', '118.215.199.186', '118.215.207.186', '118.215.215.186', '118.215.231.186', '118.215.255.186', '118.215.39.186', '118.215.63.186', '118.215.7.186', '118.215.79.186', '118.215.87.186', '118.215.95.186',
'202.43.63.186',
'69.192.31.186',
'72.247.111.186',
'88.221.43.186',
'92.122.143.186', '92.123.151.186', '92.123.159.186', '92.123.163.186', '92.123.167.186', '92.123.179.186', '92.123.183.186');
// JH
$paypal_iplist = array_merge($paypal_iplist, $paypal_iplist2, $paypal_iplist3,
// Added JH 2013-10-12
$paypal_iplist_api,
$paypal_iplist_api_aa,
$paypal_iplist_api_3t_aa,
$paypal_iplist_api_aa_3t,
$paypal_iplist_notify,
$paypal_iplist_ipnb
// JH
);
$paypal_iplist = array_merge($paypal_iplist, $paypal_iplist2, $paypal_iplist3);
$this->debugLog($paypal_iplist, 'checkPaypalIps PRODUCTION', 'debug', false);
}
$this->debugLog($_SERVER['REMOTE_ADDR'], 'checkPaypalIps REMOTE ADDRESS', 'debug', false);
// test if the remote IP connected here is a valid IP address
if (!in_array($_SERVER['REMOTE_ADDR'], $paypal_iplist)) {
$text = "Error with REMOTE IP ADDRESS = " . $_SERVER['REMOTE_ADDR'] . ".
The remote address of the script posting to this notify script does not match a valid PayPal IP address\n
These are the valid IP Addresses: " . implode(",", $paypal_iplist) .
"The Order ID received was: " . $order_number;
$this->debugLog($text, 'checkPaypalIps', 'error', false);
return false;
}
return true;
}
protected function validateIpnContent($paypal_data) {
$test_ipn = (array_key_exists('test_ipn', $paypal_data)) ? $paypal_data['test_ipn'] : 0;
if ($test_ipn == 1) {
//return true;
}
// Paypal wants to open the socket in SSL
$port = 443;
$paypal_url = $this->_getPaypalURL('ssl://', false);
$paypal_url_header = $this->_getPaypalURL('', false);
$protocol = 'ssl://';
/*
* Before we can trust the contents of the message, we must first verify that the message came from PayPal.
* To verify the message, we must send back the contents in the exact order they
* were received and precede it with the command _notify-validate,
*/
// read the post from PayPal system and add 'cmd'
$post_msg = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($paypal_data as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = str_replace('\r\n', "QQLINEBREAKQQ", $value);
$value = urlencode(stripslashes($value));
$value = str_replace("QQLINEBREAKQQ", "\r\n", $value);
} else {
$value = urlencode($value);
}
$post_msg .= "&$key=$value";
}
$header="POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "User-Agent: PHP/" . phpversion () . "\r\n";
$header .= "Referer: " . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . @$_SERVER['QUERY_STRING'] . "\r\n";
$header .= "Server: " . $_SERVER['SERVER_SOFTWARE'] . "\r\n";
$header .= "Host: " . $paypal_url_header . ":" . $port . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen ($post_msg) . "\r\n";
//$header .= "Accept: */*\r\n\r\n";
$header .="Connection: close\r\n\r\n";
$fps = fsockopen($paypal_url, $port, $errno, $errstr, 30);
$valid_ipn = false;
if (!$fps) {
$this->debugLog(JText::sprintf('VMPAYMENT_PAYPAL_ERROR_POSTING_IPN', $errstr, $errno), 'validateIpnContent', 'error' , false);
} else {
$return = fputs($fps, $header . $post_msg);
if ($return===false) {
$this->debugLog("FALSE", 'validateIpnContent FPUTS', 'error', false);
return FALSE;
}
$res = '';
while (!feof($fps)) {
$res .= fgets($fps, 1024);
}
fclose($fps);
// Inspect IPN validation result and act accordingly
$valid_ipn = strstr($res, "VERIFIED");
if (!$valid_ipn) {
if (strstr($res, "INVALID")) {
$errorInfo=array("paypal_data" =>$paypal_data, 'post_msg'=> $post_msg, 'paypal_res' =>$res);
$this->debugLog($errorInfo, JText::_('VMPAYMENT_PAYPAL_ERROR_IPN_VALIDATION'), 'error', false);
} else {
$this->debugLog(JText::_('VMPAYMENT_PAYPAL_ERROR_IPN_VALIDATION') . ": NO ANSWER FROM PAYPAL", 'validateIpnContent', 'error', false);
}
}
}
$this->debugLog('valid_ipn: ' . $valid_ipn, 'validateIpnContent', 'debug', false);
return $valid_ipn;
}
protected function _check_txn_id_already_processed($payments, $txn_id) {
if ($this->order['details']['BT']->order_status == $this->_method->status_success) {
foreach ($payments as $payment) {
$paypal_data = json_decode($payment->paypal_fullresponse);
if ($paypal_data->txn_id == $txn_id) {
return true;
}
}
}
return false;
}
protected function _check_email_amount_currency($payments, $paypal_data) {
/*
* TODO Not checking yet because config do not have primary email address
* Primary email address of the payment recipient (that is, the merchant).
* If the payment is sent to a non-primary email address on your PayPal account,
* the receiver_email is still your primary email.
*/
if ($this->_method->paypalproduct =="std") {
if (strcasecmp($paypal_data['receiver_email'],$this->merchant_email)!=0 ) {
$errorInfo=array("paypal_data" =>$paypal_data, 'merchant_email' =>$this->merchant_email);
$this->debugLog($errorInfo, 'IPN notification: wrong merchant_email', 'error', false);
return false;
}
}
if (($payments[0]->payment_order_total == $paypal_data['mc_gross']) and ($this->currency_code_3 == $paypal_data['mc_currency'])) {
return TRUE;
}
$errorInfo=array("paypal_data" =>$paypal_data, 'payment_order_total' =>$payments[0]->payment_order_total, 'currency_code_3'=>$this->currency_code_3);
$this->debugLog($errorInfo, 'IPN notification with invalid amount or currency or email', 'error', false);
return FALSE;
}
static function getPaypalCreditCards() {
return array(
'Visa',
'Mastercard',
'Amex',
'Discover',
'Maestro',
);
}
function _is_full_refund($payment, $paypal_data) {
if (($payment->payment_order_total == (-1 * $paypal_data['mc_gross']))) {
return TRUE;
} else {
return FALSE;
}
}
function handleResponse() {
if ($this->response) {
if ($this->response['ACK'] == 'Failure' || $this->response['ACK'] == 'FailureWithWarning') {
$error = '';
$public_error = '';
for ($i = 0; isset($this->response["L_ERRORCODE" . $i]); $i++) {
$error .= $this->response["L_ERRORCODE" . $i];
$message = isset($this->response["L_LONGMESSAGE" . $i]) ? $this->response["L_LONGMESSAGE" . $i] : $this->response["L_SHORTMESSAGE" . $i];
$error .= ": " . $message . "
";
}
if ($this->_method->debug) {
$public_error = $error;
}
$this->debugLog($this->response, 'handleResponse:', 'debug');
VmError($error, $public_error);
return false;
} elseif ($this->response['ACK'] == 'Success' || $this->response['ACK'] == 'SuccessWithWarning' || $this->response['TRANSACTIONID'] != NULL || $this->response['PAYMENTINFO_0_TRANSACTIONID'] != NULL) {
return true;
} else {
// Unexpected ACK type. Log response and inform the buyer that the
// transaction must be manually investigated.
$error = '';
$public_error = '';
$error="Unexpected ACK type:". $this->response['ACK'];
$this->debugLog($this->response, 'Unexpected ACK type:', 'debug');
if ($this->_method->debug) {
$public_error = $error;
}
VmError($error, $public_error);
return false;
}
}
}
function onShowOrderBEPayment($data) {
$showOrderBEFields = $this->getOrderBEFields();
$prefix = 'PAYPAL_RESPONSE_';
$html = '';
if ($data->ACK == 'SuccessWithWarning' &&
$data->L_ERRORCODE0 == self::FMF_PENDED_ERROR_CODE &&
$data->PAYMENTSTATUS == "Pending"
) {
$showOrderField = 'L_SHORTMESSAGE0';
$html .= $this->paypalPlugin->getHtmlRowBE($prefix . $showOrderField, $this->highlight($data->$showOrderField));
}
if (($data->ACK == 'Failure' OR $data->ACK == 'FailureWithWarning')) {
$showOrderField = 'L_SHORTMESSAGE0';
$html .= $this->paypalPlugin->getHtmlRowBE($prefix . 'ERRORMSG', $this->highlight($data->$showOrderField));
$showOrderField = 'L_LONGMESSAGE0';
$html .= $this->paypalPlugin->getHtmlRowBE($prefix . 'ERRORMSG', $this->highlight($data->$showOrderField));
}
foreach ($showOrderBEFields as $key => $showOrderBEField) {
if (($showOrderBEField == 'PAYMENTINFO_0_REASONCODE' and $data->$showOrderBEField != 'None') OR
($showOrderBEField == 'PAYMENTINFO_0_ERRORCODE' and $data->$showOrderBEField != 0) OR
($showOrderBEField != 'PAYMENTINFO_0_REASONCODE' and $showOrderBEField != 'PAYMENTINFO_0_ERRORCODE')
) {
if (isset($data->$showOrderBEField)) {
$key = $prefix . $key;
$html .= $this->paypalPlugin->getHtmlRowBE($key, $data->$showOrderBEField);
}
}
}
return $html;
}
function onShowOrderBEPaymentByFields($payment) {
return NULL;
}
/*********************/
/* Log and Reporting */
/*********************/
public function debug($subject, $title = '', $echo = true) {
$debug = '';
$debug .= ($title) ? '
' . $title . ':' : '';
//$debug .= '
';
$debug .= str_replace("=>", "⇒", str_replace("Array", "Array", nl2br(str_replace(" ", " ", print_r($subject, true)))));
//$debug .= '';
$debug .= '
';
if ($echo) {
echo $debug;
} else {
return $debug;
}
}
function highlight($string) {
return '' . $string . '';
}
public function debugLog($message, $title = '', $type = 'message', $echo = false, $doVmDebug=false) {
//Nerver log the full credit card number nor the CVV code.
if (is_array($message)) {
if (array_key_exists('ACCT', $message)) {
$message['ACCT'] = "**** **** **** " . substr($message['ACCT'], -4);
}
if (array_key_exists('CVV2', $message)) {
$message['CVV2'] = str_repeat('*', strlen($message['CVV2']));
}
if (array_key_exists('signature', $message)) {
$message['signature'] = '**MASKED**';
}
if (array_key_exists('api_password', $message)) {
$message['api_password'] = '**MASKED**';
}
}
if ($this->_method->debug) {
$this->debug($message, $title, true);
}
if ($echo) {
echo $message . '
';
}
$this->paypalPlugin->debugLog($message, $title, $type, $doVmDebug);
}
}