_loggable = TRUE;
$this->tableFields = array_keys ($this->getTableSQLFields ());
$this->_tablepkey = 'id';
$this->_tableId = 'id';
$varsToPush = $this->getVarsToPush ();
$this->setConfigParameterable ($this->_configTableFieldName, $varsToPush);
}
/**
* @return string
*/
public function getVmPluginCreateTableSQL () {
return $this->createTableSQL ('Payment Klarna Table');
}
/**
* @return array
*/
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 DEFAULT \'0.00000\'',
'payment_fee' => 'decimal(10,2)',
'tax_id' => 'smallint(1)',
'klarna_eid' => 'int(10)',
'klarna_status_code' => 'tinyint(4)',
'klarna_status_text' => 'varchar(255)',
'klarna_invoice_no' => 'varchar(255)',
'klarna_log' => 'varchar(255)',
'klarna_pclass' => 'int(1)',
'klarna_pdf_invoice' => 'varchar(512)',
);
return $SQLfields;
}
/**
* @param $name
* @param $id
* @param $data
* @return bool
*/
function plgVmDeclarePluginParamsPaymentVM3( &$data) {
return $this->declarePluginParams('payment', $data);
}
/**
* @param $name
* @param $id
* @param $table
* @return bool
*/
function plgVmSetOnTablePluginParamsPayment ($name, $id, &$table) {
return $this->setOnTablePluginParams ($name, $id, $table);
}
/**
* @param $product
* @param $productDisplay
* @return bool
*/
function plgVmOnProductDisplayPayment ($product, &$productDisplay) {
$vendorId = 1;
if ($this->getPluginMethods ($vendorId) === 0) {
return FALSE;
}
if (!class_exists ('klarna_productPrice')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_productprice.php');
}
if (!class_exists ('VirtueMartCart')) {
require(VMPATH_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart ();
foreach ($this->methods as $method) {
$type = NULL;
$cData = KlarnaHandler::getcData ($method, $this->getCartAddress ($cart, $type, FALSE));
if ($cData['active'] and in_array ('part', $cData['payments_activated'])) {
//if (!empty($product->prices)) { // no price is set
if (!empty($product->prices['salesPrice'])) {
$productPrice = new klarna_productPrice($cData);
if ($productViewData = $productPrice->showProductPrice ($product, $cart)) {
$productDisplayHtml = $this->renderByLayout ('productprice_layout', $productViewData, $method->payment_element, 'payment');
$productDisplay[] = $productDisplayHtml;
}
}
}
}
return TRUE;
}
/*
*
*/
/**
* @param $cart
* @param $countryCode
* @param $countryId
* @param string $fld
*/
function _getCountryCode ($cart = NULL, &$countryCode, &$countryId, $fld = 'country_3_code') {
if ($cart == '') {
if (!class_exists ('VirtueMartCart')) {
require(VMPATH_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart ();
}
$type = NULL;
$address = $this->getCartAddress ($cart, $type, FALSE);
if (vRequest::getVar ('klarna_country_2_code') == 'se') {
$countryId = ShopFunctions::getCountryIDByName ('se');
$countryCode = shopFunctions::getCountryByID ($countryId, $fld);
} elseif (!isset($address['virtuemart_country_id']) or empty($address['virtuemart_country_id'])) {
$countryCode = KlarnaHandler::getVendorCountry ($fld);
$countryId = ShopFunctions::getCountryIDByName ($countryCode);
} else {
$countryId = $address['virtuemart_country_id'];
$countryCode = shopFunctions::getCountryByID ($address['virtuemart_country_id'], $fld);
}
}
/**
* @param $cart
* @param $type
* @param bool $STsameAsBT
* @return mixed
*/
function getCartAddress ($cart, &$type, $STsameAsBT = TRUE) {
if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) {
$st = $cart->BT;
$type = 'BT';
if ($STsameAsBT and $cart->ST and !$cart->STsameAsBT) {
vmInfo (vmText::_ ('VMPAYMENT_KLARNA_SHIPTO_SAME_AS_BILLTO'));
$cart->STsameAsBT = 1;
$cart->setCartIntoSession ();
}
} elseif ($cart->BT == 0 or empty($cart->BT)) {
$st = $cart->BT;
$type = 'BT';
} else {
$st = $cart->ST;
$type = 'ST';
}
return $st;
}
/**
* @param VirtueMartCart $cart
* @param string $fld
* @return null
*/
function _getCartAddressCountryId (VirtueMartCart $cart, $fld = 'country_3_code') {
$type = "";
$address = $this->getCartAddress ($cart, $type, FALSE);
if (!isset($address['virtuemart_country_id'])) {
return NULL;
}
return $address['virtuemart_country_id'];
}
/**
* @param $virtuemart_order_id
* @param string $fld
* @return string
*/
function getCountryCodeByOrderId ($virtuemart_order_id, $fld = 'country_3_code') {
$db = JFactory::getDBO ();
$q = 'SELECT `virtuemart_country_id`, `address_type` FROM #__virtuemart_order_userinfos WHERE virtuemart_order_id=' . $virtuemart_order_id;
$db->setQuery ($q);
$results = $db->loadObjectList ();
if (count ($results) == 1) {
$virtuemart_country_id = $results[0]->virtuemart_country_id;
} else {
foreach ($results as $result) {
if ($result->address_type == 'ST') {
$virtuemart_country_id = $result->virtuemart_country_id;
break;
}
}
}
return shopFunctions::getCountryByID ($virtuemart_country_id, $fld);
}
/**
* plgVmDisplayListFEPayment
* This event is fired to display the plugin methods in the cart (edit shipment/payment) for example
*
* @param object $cart Cart object
* @param integer $selected ID of the method selected
* @return boolean True on success, false on failures, null when this plugin was not selected.
* On errors, JError::raiseWarning (or JError::raiseError) must be used to set a message.
*
* @author Valerie Isaksen
*/
public function plgVmDisplayListFEPayment (VirtueMartCart $cart, $selected = 0, &$htmlIn) {
$html = $this->displayListFEPayment ($cart, $selected);
if (!empty($html)) {
$htmlIn[] = $html;
}
}
/**
* @param VirtueMartCart $cart VirtueMartCart
* @param $selected
* @return array|bool
*/
protected function displayListFEPayment (VirtueMartCart $cart, $selected) {
if (!class_exists ('Klarna_payments')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_payments.php');
}
if ($this->getPluginMethods ($cart->vendorId) === 0) {
if (empty($this->_name)) {
$app = JFactory::getApplication ();
$app->enqueueMessage (vmText::_ ('COM_VIRTUEMART_CART_NO_' . strtoupper ($this->_psType)));
return FALSE;
} else {
return FALSE;
}
}
$html = array();
foreach ($this->methods as $method) {
$temp = $this->getListFEPayment ($cart, $method);
if (!empty($temp)) {
$html[] = $temp;
}
}
if (!empty($html)) {
$this->loadScriptAndCss ();
}
return $html;
}
/**
* @param VirtueMartCart $cart
* @param $method
* @return null|string
*/
protected function getListFEPayment (VirtueMartCart $cart, $method) {
$cart_currency_code = ShopFunctions::getCurrencyByID ($cart->pricesCurrency, 'currency_code_3');
$country_code = NULL;
$countryId = 0;
$this->_getCountryCode ($cart, $country_code, $countryId);
if (!($cData = $this->checkCountryCondition ($method, $country_code, $cart))) {
return NULL;
}
try {
$pclasses = KlarnaHandler::getPClasses (NULL, KlarnaHandler::getKlarnaMode ($method, $cData['country_code_3']), $cData);
}
catch (Exception $e) {
vmError ($e->getMessage (), $e->getMessage ());
return NULL;
}
$specCamp = 0;
$partPay = 0;
$this->getNbPClasses ($pclasses, $specCamp, $partPay);
$sessionKlarnaData = $this->getKlarnaSessionData ();
$klarna_paymentmethod = "";
if (isset($sessionKlarnaData->klarna_paymentmethod)) {
$klarna_paymentmethod = $sessionKlarnaData->klarna_paymentmethod;
}
$html = '';
$checked = 'checked="checked"';
$payments = new klarna_payments($cData, KlarnaHandler::getShipToAddress ($cart));
if (in_array ('invoice', $cData['payments_activated'])) {
$payment_params = $payments->get_payment_params ($method, 'invoice', $cart);
$payment_form = $this->renderByLayout ('payment_form',
array('payment_params' => $payment_params,
'payment_currency_info' => $payment_params['payment_currency_info']
)
);
$selected = ($klarna_paymentmethod == 'klarna_invoice' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : "";
$html .= $this->renderByLayout ('displaypayment', array(
'stype' => 'invoice',
'id' => $payment_params['id'],
'module' => $payment_params['module'],
'klarna_form' => $payment_form,
'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id,
'klarna_paymentmethod' => $klarna_paymentmethod,
'selected' => $selected
));
}
if (in_array ('part', $cData['payments_activated'])) {
if (strtolower ($country_code) == 'nld') {
// Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros. So the price check has been moved here
if (!KlarnaHandler::checkPartNLpriceCondition ($cart)) {
// We can't show our payment options for Dutch customers
// if price exceeds 250 euro. Will be replaced with ILT in
// the future.
$partPay = 0;
}
}
if (!KlarnaHandler::checkPartpriceCondition ($cData, $cart)) {
$partPay = 0;
}
if ($partPay > 0) {
if ($payment_params = $payments->get_payment_params ($method, 'part', $cart, $cData['virtuemart_currency_id'], $cData['vendor_currency'])) {
$payment_form = $this->renderByLayout ('payment_form', array('payment_params' => $payment_params, 'payment_currency_info' => $payment_params['payment_currency_info'],), 'klarna', 'payment');
$selected = ($klarna_paymentmethod == 'klarna_part' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : "";
$html .= $this->renderByLayout ('displaypayment', array(
'stype' => 'part',
'id' => $payment_params['id'],
'module' => $payment_params['module'],
'klarna_form' => $payment_form,
'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id,
'klarna_paymentmethod' => $klarna_paymentmethod,
'selected' => $selected
));
}
}
}
// not tested yet
/*
if ( $specCamp > 0) {
if ($payment_params = $payments->get_payment_params ($method, 'spec', $cart, $cData['virtuemart_currency_id'])) {
$payment_form = $this->renderByLayout ('payment_form', array('payment_params' => $payment_params, 'payment_currency_info' => $payment_params['payment_currency_info'],), 'klarna', 'payment');
$selected = ($klarna_paymentmethod == 'klarna_spec' AND $method->virtuemart_paymentmethod_id == $cart->virtuemart_paymentmethod_id) ? $checked : "";
$html .= $this->renderByLayout ('displaypayment', array(
'stype' => 'spec',
'id' => $payment_params['id'],
'module' => $payment_params['module'],
'klarna_form' => $payment_form,
'virtuemart_paymentmethod_id' => $method->virtuemart_paymentmethod_id,
'klarna_paymentmethod' => $klarna_paymentmethod,
'selected' => $selected
));
}
}
*/
return $html;
}
/**
* Count the number of Payment Classes: Partial Payments, and Special campaigns
*
* @param $pClasses
* @param $specCamp
* @param $partPay
*/
function getNbPClasses ($pClasses, &$specCamp, &$partPay) {
$specCamp = 0;
$partPay = 0;
foreach ($pClasses as $pClass) {
if ($pClass->getType () == KlarnaPClass::SPECIAL) {
$specCamp += 1;
}
if ($pClass->getType () == KlarnaPClass::CAMPAIGN ||
$pClass->getType () == KlarnaPClass::ACCOUNT ||
$pClass->getType () == KlarnaPClass::FIXED ||
$pClass->getType () == KlarnaPClass::DELAY
) {
$partPay += 1;
}
}
}
/**
* @return mixed|null
*/
function getKlarnaSessionData () {
$session = JFactory::getSession ();
$sessionKlarna = $session->get ('Klarna', 0, 'vm');
if ($sessionKlarna) {
$sessionKlarnaData = (object) json_decode ($sessionKlarna ,true);
$sessionKlarnaData->KLARNA_DATA=(array)$sessionKlarnaData->KLARNA_DATA;
return $sessionKlarnaData;
}
return NULL;
}
/**
* @param $method
* @param $country_code
* @param $cart
* @return array|bool|null
*/
function checkCountryCondition ($method, $country_code, $cart) {
if (!class_exists ('CurrencyDisplay')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php');
}
$active_country = "klarna_active_" . strtolower ($country_code);
if (!isset($method->$active_country) or !$method->$active_country) {
return FALSE;
}
if (empty($country_code)) {
$msg = vmText::_ ('VMPAYMENT_KLARNA_GET_SWEDISH_ADDRESS');
$country_code = "swe";
vmWarn ($msg);
//return false;
}
/*
if (strtolower ($country_code) == 'nld') {
if(! KlarnaHandler::checkPartNLpriceCondition ($cart)) {
// We can't show our payment options for Dutch customers
// if price exceeds 250 euro. Will be replaced with ILT in
// the future.
return FALSE;
}
}
*/
// Get the country settings
if (!class_exists ('KlarnaHandler')) {
require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnahandler.php');
}
$cData = KlarnaHandler::getCountryData ($method, $country_code);
if ($cData['eid'] == '' || $cData['eid'] == 0) {
return FALSE;
}
return $cData;
}
/**
* @param $cart
* @param $order
* @return bool|null
*/
function plgVmConfirmedOrder ($cart, $order) {
if (!($method = $this->getVmPluginMethod ($order['details']['BT']->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement ($method->payment_element)) {
return FALSE;
}
if (!class_exists ('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
$this->setInConfirmOrder($cart);
$sessionKlarnaData = $this->getKlarnaSessionData ();
try {
$result = KlarnaHandler::addTransaction ($method, $order, $sessionKlarnaData->KLARNA_DATA['pclass']);
}
catch (Exception $e) {
$log = $e->getMessage ();
vmError ($e->getMessage () . ' #' . $e->getCode (), $e->getMessage () . ' #' . $e->getCode ());
return;
//KlarnaHandler::redirectPaymentMethod('error', $e->getMessage() . ' #' . $e->getCode());
}
//vmdebug('addTransaction result', $result);
// Delete all Klarna data
//unset($sessionKlarnaData->KLARNA_DATA, $_SESSION['SSN_ADDR']);
$shipTo = KlarnaHandler::getShipToAddress ($cart);
$modelOrder = VmModel::getModel ('orders');
if ($result['status_code'] == KlarnaFlags::DENIED) {
$order['customer_notified'] = 0;
$order['order_status'] = $method->status_denied;
$order['comments'] = vmText::sprintf ('VMPAYMENT_KLARNA_PAYMENT_KLARNA_STATUS_DENIED');
if ($method->delete_order) {
$order['comments'] .= "
" . $result['status_text'];
}
$modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE);
vmdebug ('addTransaction remove order?', $method->delete_order);
if ($method->delete_order) {
$modelOrder->remove (array('virtuemart_order_id' => $order['details']['BT']->virtuemart_order_id));
} else {
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['payment_name'] = $this->renderKlarnaPluginName ($method, $order['details']['BT']->virtuemart_country_id, $shipTo, $order['details']['BT']->order_total, $order['order_currency']);
$dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id;
$dbValues['order_payment'] = $order['details']['BT']->order_payment;
$dbValues['klarna_pclass'] = $sessionKlarnaData->KLARNA_DATA['PCLASS'];
$dbValues['klarna_log'] = '';
$dbValues['klarna_status_code'] = $result['status_code'];
$dbValues['klarna_status_text'] = $result['status_text'];
$this->storePSPluginInternalData ($dbValues);
}
$app = JFactory::getApplication ();
$app->enqueueMessage ($result['status_text']);
$app->redirect (JRoute::_ ('index.php?option=com_virtuemart&view=cart&task=editpayment'));
} else {
$invoiceno = $result[1];
if ($invoiceno && is_numeric ($invoiceno)) {
//Get address id used for this order.
//$country = $sessionKlarnaData->KLARNA_DATA['country'];
// $lang = KlarnaHandler::getLanguageForCountry($method, KlarnaHandler::convertToThreeLetterCode($country));
// $d['order_payment_name'] = $kLang->fetch('MODULE_INVOICE_TEXT_TITLE', $lang);
// Add a note in the log
$log = vmText::sprintf ('VMPAYMENT_KLARNA_INVOICE_CREATED_SUCCESSFULLY', $invoiceno);
// Prepare data that should be stored in the database
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['payment_name'] = $this->renderKlarnaPluginName ($method, $order['details']['BT']->virtuemart_country_id, $shipTo, $order['details']['BT']->order_total, $order['details']['BT']->order_currency);
$dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id;
$dbValues['order_payment'] = $order['details']['BT']->order_payment;
$dbValues['order_payment_tax'] = $order['details']['BT']->order_payment_tax;
$dbValues['klarna_pclass'] = $sessionKlarnaData->KLARNA_DATA['pclass'];
$dbValues['klarna_invoice_no'] = $invoiceno;
$dbValues['klarna_log'] = $log;
$dbValues['klarna_eid'] = $result['eid'];
$dbValues['klarna_status_code'] = $result['status_code'];
$dbValues['klarna_status_text'] = $result['status_text'];
$this->storePSPluginInternalData ($dbValues);
/*
* Klarna's order status
* Integer - 1,2 or 3.
* 1 = OK: KlarnaFlags::ACCEPTED
* 2 = Pending: KlarnaFlags::PENDING
* 3 = Denied: KlarnaFlags::DENIED
*/
if ($result['status_code'] == KlarnaFlags::PENDING) {
/* if Klarna's order status is pending: add it in the history */
/* The order is under manual review and will be accepted or denied at a later stage.
Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */
$order['order_status'] = $method->status_pending;
} else {
$order['order_status'] = $method->status_success;
}
$order['customer_notified'] = 1;
$order['comments'] = $log;
$modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE);
$html = $this->renderByLayout ('orderdone', array(
'payment_name' => $dbValues['payment_name'],
'klarna_invoiceno' => $invoiceno));
if ($result['eid'] == VMPAYMENT_KLARNA_MERCHANT_ID_DEMO) {
$html .= "
" . vmText::_ ('VMPAYMENT_KLARNA_WARNING') . "
";
}
$session = JFactory::getSession ();
$session->clear ('Klarna', 'vm');
//We delete the old stuff
$cart->emptyCart ();
vRequest::setVar ('html', $html);
return TRUE;
} else {
vmError ('Error with invoice number');
}
}
}
/**
* @param $orderDetails
* @param $data
* @return null
*/
function plgVmOnUserInvoice ($orderDetails, &$data) {
if (!($method = $this->getVmPluginMethod ($orderDetails['virtuemart_paymentmethod_id']))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement ($method->payment_element)) {
return NULL;
}
$data['invoice_number'] = 'reservedByPayment_' . $orderDetails['order_number']; // Nerver send the invoice via email
}
/**
* @param $virtuemart_paymentmethod_id
* @param $paymentCurrencyId
* @return bool|null
*/
function plgVmGetPaymentCurrency ($virtuemart_paymentmethod_id, &$paymentCurrencyId) {
if (!($method = $this->getVmPluginMethod ($virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement ($method->payment_element)) {
return FALSE;
}
$paymentCurrencyId = $this->getKlarnaPaymentCurrency ($method);
}
/**
* @param $method
* @return int
*/
function getKlarnaPaymentCurrency ($method) {
if (!class_exists ('VirtueMartCart')) {
require(VMPATH_SITE . DS . 'helpers' . DS . 'cart.php');
}
$cart = VirtueMartCart::getCart (FALSE);
$country = NULL;
$countryId = 0;
$this->_getCountryCode ($cart, $country, $countryId);
$cData = KlarnaHandler::countryData ($method, $country);
return shopFunctions::getCurrencyIDByName ($cData['currency_code']);
}
/**
*
* An order gets cancelled, because order status='X'
*
* @param $order
* @param $old_order_status
* @return bool|null
*/
function plgVmOnCancelPayment ($order, $old_order_status) {
if (!$this->selectedThisByMethodId ($order->virtuemart_paymentmethod_id)) {
return NULL; // Another method was selected, do nothing
}
if (!($method = $this->getVmPluginMethod ($order->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!($payments = $this->_getKlarnaInternalData ($order->virtuemart_order_id))) {
vmError (vmText::sprintf ('VMPAYMENT_KLARNA_ERROR_NO_DATA', $order->virtuemart_order_id));
return NULL;
}
// Status code is === 3==> active invoice. Cannot be be deleted
// the invoice is active
//if ($order->order_status == $method->status_success) {
if ($invNo = $this->_getKlarnaInvoiceNo ($payments)) {
//vmDebug('order',$order);return;
$country = $this->getCountryCodeByOrderId ($order->virtuemart_order_id);
$klarna = new Klarna_virtuemart();
$cData = KlarnaHandler::countryData ($method, $country);
$klarna->config ($cData['eid'], $cData['secret'], $cData['country_code'], NULL, $cData['currency_code'], $cData['mode']);
try {
//remove a passive invoice from Klarna.
$result = $klarna->deleteInvoice ($invNo);
if ($result) {
$message = vmText::_ ('VMPAYMENT_KLARNA_INVOICE_DELETED') . ":" . $invNo;
} else {
$message = vmText::_ ('VMPAYMENT_KLARNA_INVOICE_NOT_DELETED') . ":" . $invNo;
}
$dbValues['order_number'] = $order->order_number;
$dbValues['virtuemart_order_id'] = $order->virtuemart_order_id;
$dbValues['virtuemart_paymentmethod_id'] = $order->virtuemart_paymentmethod_id;
$dbValues['klarna_invoice_no'] = 0; // it has been deleted
$dbValues['klarna_pdf_invoice'] = 0; // it has been deleted
$dbValues['klarna_log'] = $message;
$dbValues['klarna_eid'] = $cData['eid'];
$this->storePSPluginInternalData ($dbValues);
VmInfo ($message);
}
catch (Exception $e) {
$log = $e->getMessage () . " (#" . $e->getCode () . ")";
if ($e->getCode () == '8113') {
VmError ('invoice_not_passive');
}
if ($e->getCode () != 8101) { // unkown_order
$this->_updateKlarnaInternalData ($order, $log, $invNo);
VmError ($e->getMessage () . " (#" . $e->getCode () . ")");
return FALSE;
}
}
}
return TRUE;
}
/**
* @param $payments
* @param string $primaryKey
* @return mixed
*/
function _getKlarnaInvoiceNo ($payments, &$primaryKey = '') {
$nb = count ($payments);
$primaryKey = $payments[$nb - 1]->id;
return $payments[$nb - 1]->klarna_invoice_no;
}
/**
* @param $payments
* @return mixed
*/
function _getKlarnaPlcass ($payments) {
$nb = count ($payments);
return $payments[$nb - 1]->klarna_pclass;
}
/**
* @param $payments
* @return mixed
*/
function _getKlarnaStatusCode ($payments) {
$nb = count ($payments);
return $payments[$nb - 1]->klarna_status_code;
}
/**
* @param $type
* @param $name
* @param $render
*/
/*
function plgVmOnSelfCallFE ($type, $name, &$render) {
if ($name != $this->_name || $type != 'vmpayment') {
return FALSE;
}
//Klarna Ajax
require (JPATH_VMKLARNAPLUGIN . '/klarna/helpers/klarna_ajax.php');
if (!class_exists ('VmModel')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'vmmodel.php');
}
$model = VmModel::getModel ('paymentmethod');
$payment = $model->getPayment ();
if (!class_exists ('vmParameters')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'parameterparser.php');
}
$parameters = new vmParameters($payment, $payment->payment_element, 'plugin', 'vmpayment');
$method = $parameters->getParamByName ('data');
$country = vRequest::getWord ('country');
$country = KlarnaHandler::convertToThreeLetterCode ($country);
if (!class_exists ('klarna_virtuemart')) {
require (JPATH_VMKLARNAPLUGIN . '/klarna/helpers/klarna_virtuemart.php');
}
$settings = KlarnaHandler::getCountryData ($method, $country);
$klarna = new Klarna_virtuemart();
$klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']), VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE);
$SelfCall = new KlarnaAjax($klarna, (int)$settings['eid'], JPATH_VMKLARNAPLUGIN, Juri::base ());
$action = vRequest::getWord ('action');
$jlang = JFactory::getLanguage ();
$currentLang = substr ($jlang->getDefault (), 0, 2);
$newIso = vRequest::getWord ('newIso');
if ($currentLang != $newIso) {
$iso = array(
"sv" => "sv-SE",
"da" => "da-DK",
"en" => "en-GB",
"de" => "de-DE",
"nl" => "nl-NL",
"nb" => "nb-NO",
"fi" => "fi-FI");
if (array_key_exists ($newIso, $iso)) {
$jlang->load ('plg_vmpayment_klarna', JPATH_ADMINISTRATOR, $iso[$newIso], TRUE);
}
}
echo $SelfCall->$action();
jexit ();
}
*/
/**
* @author Patrick Kohl
* @param $type
* @param $name
* @param $render
*/
function plgVmOnSelfCallBE ($type, $name, &$render) {
if ($name != $this->_name || $type != 'vmpayment') {
return FALSE;
}
// fetches PClasses From XML file
$call = vRequest::getWord ('call');
$this->$call();
// jexit();
}
/**
*
* Download Pdf Invoice
*
* @author Valérie Isaksen
*
*/
/**
* @return int|null|string
*/
function downloadInvoicePdf () {
if (!class_exists ('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
if (!class_exists ('JFile')) {
require(JPATH_SITE . DS . 'libraries' . DS . 'joomla' . DS . 'filesystem' . DS . 'file.php');
}
$payment_methodid = vRequest::getInt ('payment_methodid');
$orderNumber = vRequest::getString ('order_number');
$orderPass = vRequest::getString ('order_pass');
if (!($method = $this->getVmPluginMethod ($payment_methodid))) {
return NULL; // Another method was selected, do nothing
}
$modelOrder = VmModel::getModel ('orders');
// If the user is not logged in, we will check the order number and order pass
$virtuemart_order_id = $modelOrder->getOrderIdByOrderPass ($orderNumber, $orderPass);
if (empty($virtuemart_order_id)) {
VmError ('Invalid order_number/password ' . vmText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'), 'Invalid order_number/password ' . vmText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'));
return 0;
}
if (!($payments = $this->_getKlarnaInternalData ($virtuemart_order_id))) {
return '';
}
foreach ($payments as $payment) {
if (!empty($payment->klarna_pdf_invoice)) {
$path = VmConfig::get ('forSale_path', 0);
$path .= DS . 'invoices' . DS;
$fileName = $path . $payment->klarna_pdf_invoice;
break;
}
}
if (file_exists ($fileName)) {
header ("Cache-Control: public");
header ("Content-Transfer-Encoding: binary\n");
header ('Content-Type: application/pdf');
$contentDisposition = 'attachment';
$agent = strtolower ($_SERVER['HTTP_USER_AGENT']);
if (strpos ($agent, 'msie') !== FALSE) {
$fileName = preg_replace ('/\./', '%2e', $fileName, substr_count ($fileName, '.') - 1);
}
header ("Content-Disposition: $contentDisposition; filename=\"$payment->klarna_pdf_invoice\"");
$contents = file_get_contents ($fileName);
echo $contents;
}
return;
}
/*
* @author Valérie Isaksen
*
* @return int|null
*/
function checkOrderStatus () {
if (!class_exists ('VirtueMartModelOrders')) {
require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php');
}
$payment_methodid = vRequest::getInt ('payment_methodid');
//$invNo = vRequest::getWord ('invNo');
$orderNumber = vRequest::getString ('order_number');
$orderPass = vRequest::getString ('order_pass');
if (!($method = $this->getVmPluginMethod ($payment_methodid))) {
return NULL; // Another method was selected, do nothing
}
$modelOrder = VmModel::getModel ('orders');
// If the user is not logged in, we will check the order number and order pass
$orderId = $modelOrder->getOrderIdByOrderPass ($orderNumber, $orderPass);
if (empty($orderId)) {
VmError ('Invalid order_number/password ' . vmText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'), 'Invalid order_number/password ' . vmText::_ ('COM_VIRTUEMART_RESTRICTED_ACCESS'));
return 0;
}
if (!($payments = $this->_getKlarnaInternalData ($orderId))) {
return '';
}
$invNo = $this->_getKlarnaInvoiceNo ($payments);
$country = $this->getCountryCodeByOrderID ($orderId);
$settings = KlarnaHandler::countryData ($method, $country);
$klarna_order_status = KlarnaHandler::checkOrderStatus ($settings, KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']), $orderNumber);
vmdebug ('Klarna status', $klarna_order_status, $invNo);
if ($klarna_order_status == KlarnaFlags::ACCEPTED) {
/* if Klarna's order status is pending: add it in the history */
/* The order is under manual review and will be accepted or denied at a later stage.
Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */
$order['order_status'] = $method->status_success;
$order['comments'] = vmText::_ ('VMPAYMENT_KLARNA_PAYMENT_ACCEPTED');
$order['customer_notified'] = 0;
$dbValues['klarna_log'] = vmText::_ ('VMPAYMENT_KLARNA_PAYMENT_ACCEPTED');
} elseif ($klarna_order_status == KlarnaFlags::DENIED) {
$order['order_status'] = $method->status_denied;
$order['customer_notified'] = 1;
$dbValues['klarna_log'] = vmText::_ ('VMPAYMENT_KLARNA_PAYMENT_NOT_ACCEPTED');
$order['comments'] = vmText::_ ('VMPAYMENT_KLARNA_PAYMENT_NOT_ACCEPTED');
} else {
if ($klarna_order_status == KlarnaFlags::PENDING) {
$dbValues['klarna_log'] = vmText::_ ('VMPAYMENT_KLARNA_PAYMENT_PENDING');
} else {
$dbValues['klarna_log'] = $klarna_order_status;
}
$order['comments'] = $dbValues['klarna_log'];
$order['customer_notified'] = 0;
}
$dbValues['order_number'] = $orderNumber;
$dbValues['virtuemart_order_id'] = $orderId;
$dbValues['virtuemart_paymentmethod_id'] = $payment_methodid;
$dbValues['klarna_invoice_no'] = $invNo;
$this->storePSPluginInternalData ($dbValues);
$modelOrder->updateStatusForOneOrder ($orderId, $order, FALSE);
$app = JFactory::getApplication ();
$app->redirect ('index.php?option=com_virtuemart&view=orders&task=edit&virtuemart_order_id=' . $orderId);
// jexit();
}
/**
* @param $virtuemart_order_id
* @return mixed|string
*/
function _getTablepkeyValue ($virtuemart_order_id) {
$db = JFactory::getDBO ();
$q = 'SELECT ' . $this->_tablepkey . ' FROM `' . $this->_tablename . '` ' . 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id;
$db->setQuery ($q);
if (!($pkey = $db->loadResult ())) {
JError::raiseWarning (500, $db->getErrorMsg ());
return '';
}
return $pkey;
}
/**
* Display stored payment data for an order
*
* @see components/com_virtuemart/helpers/vmPSPlugin::plgVmOnShowOrderBEPayment()
*/
function plgVmOnShowOrderBEPayment ($virtuemart_order_id, $payment_method_id, $order) {
if (!($this->selectedThisByMethodId ($payment_method_id))) {
return NULL; // Another method was selected, do nothing
}
if (!($payments = $this->_getKlarnaInternalData ($virtuemart_order_id))) {
// JError::raiseWarning(500, $db->getErrorMsg());
return '';
}
if (!($method = $this->getVmPluginMethod ($payment_method_id))) {
return NULL; // Another method was selected, do nothing
}
$html = '
' . vmText::_ ('VMPAYMENT_KLARNA_DATE') . ' | ' . $payment->created_on . ' |