AAAAmoneybookers_gir/moneybookers_gir.xml000066600000007225151372777310014247 0ustar00 Moneybookers Giropay April 2012 Skrill Holdings Limited http://www.skrill.com Copyright (C) 2012 Skrill. http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL 2.0.6 Moneybookers is a popular payment provider authorised by the Financial Services Authority of the United Kingdom (FSA). ]]> moneybookers_gir.php en-GB.plg_vmpayment_moneybookers_gir.ini en-GB.plg_vmpayment_moneybookers_gir.ini moneybookers_gir/moneybookers_gir.php000066600000003164151372777310014234 0ustar00_loggable = true; $this->_debug = false; $this->_tablepkey = 'id'; //virtuemart_moneybookers_id'; $this->_tableId = 'id'; //'virtuemart_moneybookers_id'; } function plgVmConfirmedOrder($cart, $order, $payment_method = '') { parent::plgVmConfirmedOrder($cart, $order, "GIR"); } } // No closing tagmoneybookers_gir/index.html000066600000000037151372777310012137 0ustar00 moneybookers_gir/.htaccess000066600000000177151372777310011745 0ustar00 Order allow,deny Deny from all moneybookers_obt/moneybookers_obt.php000066600000003164151372777310014242 0ustar00_loggable = true; $this->_debug = false; $this->_tablepkey = 'id'; //virtuemart_moneybookers_id'; $this->_tableId = 'id'; //'virtuemart_moneybookers_id'; } function plgVmConfirmedOrder($cart, $order, $payment_method = '') { parent::plgVmConfirmedOrder($cart, $order, "OBT"); } } // No closing tagmoneybookers_obt/moneybookers_obt.xml000066600000007246151372777310014260 0ustar00 Moneybookers Bank Transfer April 2012 Skrill Holdings Limited http://www.skrill.com Copyright (C) 2012 Skrill. http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL 2.0.6 Moneybookers is a popular payment provider authorised by the Financial Services Authority of the United Kingdom (FSA). ]]> moneybookers_obt.php en-GB.plg_vmpayment_moneybookers_obt.ini en-GB.plg_vmpayment_moneybookers_obt.ini moneybookers_obt/index.html000066600000000037151372777310012142 0ustar00 moneybookers_obt/.htaccess000066600000000177151372777310011750 0ustar00 Order allow,deny Deny from all heidelpay/index.html000066600000000040151372777310010520 0ustar00 heidelpay/heidelpay.php000066600000053702151372777310011215 0ustar00 * @version 12.05 * @package VirtueMart * @subpackage payment * @copyright Copyright (C) Heidelberger Payment GmbH * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php */ if (!class_exists ('vmPSPlugin')) { require(JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'); } class plgVmPaymentHeidelpay extends vmPSPlugin { public static $_this = FALSE; protected $version = '13.11'; function __construct (& $subject, $config) { //if (self::$_this) // return self::$_this; parent::__construct ($subject, $config); $this->_loggable = TRUE; $this->tableFields = array_keys ($this->getTableSQLFields ()); $this->_tablepkey = 'id'; $this->_tableId = 'id'; $this->secret = strtoupper (sha1 (mt_rand (10000, mt_getrandmax ()))); $varsToPush = $this->getVarsToPush (); $this->setConfigParameterable ($this->_configTableFieldName, $varsToPush); //self::$_this = $this; } public function getVmPluginCreateTableSQL () { return $this->createTableSQL ('Payment Heidelpay'); } 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', 'unique_id' => 'varchar(48)', 'short_id' => 'varchar(14)', 'payment_code' => 'varchar(32)', 'comment' => 'text NOT NULL', 'date' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP', 'payment_methode' => 'char(2)', 'payment_type' => 'char(2)', 'transaction_mode' => 'char(18)', 'payment_name' => 'char(50)', 'processing_result' => 'char(3)', 'secret_hash' => 'char(50)', 'response_ip' => 'char(20)' ); return $SQLfields; } function plgVmOnShowOrderBEPayment ($virtuemart_order_id, $payment_id) { if (!$this->selectedThisByMethodId ($payment_id)) { return NULL; // Another method was selected, do nothing } $db = JFactory::getDBO (); $_q = 'SELECT * FROM `' . $this->_tablename . '` ' . 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id; $db->setQuery ($_q); if (!($paymentData = $db->loadObject ())) { // JError::raiseWarning(500, $db->getErrorMsg()); } $_html = '' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; if ($paymentData->processing_result == "ACK" AND $paymentData->payment_code == 80) { $_html .= ''; } elseif ($paymentData->processing_result == "ACK") { $_html .= ''; } if ($paymentData->processing_result == "NOK") { $_html .= ''; } $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= ' ' . "\n"; $_html .= '
' . JText::_ ('COM_VIRTUEMART_ORDER_PRINT_PAYMENT_LBL') . '
' . JText::_ ('VMPAYMENT_HEIDELPAY_PAYMENT_RESULT') . 'WAITINGACKNOK
' . JText::_ ('VMPAYMENT_HEIDELPAY_PAYMENT_METHOD') . '' . $paymentData->payment_methode . '.' . $paymentData->payment_type . ' (' . $paymentData->payment_name . ')
UniqeID' . $paymentData->unique_id . '
Short-ID' . $paymentData->short_id . '
' . JText::_ ('VMPAYMENT_HEIDELPAY_COMMENT') . '' . $paymentData->comment . '
' . "\n"; return $_html; } function plgVmOnConfirmedOrderStorePaymentData ($virtuemart_order_id, $orderData, $priceData) { if (!$this->selectedThisPayment ($this->_pelement, $orderData->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } return FALSE; } 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; } $session = JFactory::getSession (); $return_context = $session->getId (); $this->_debug = $method->HEIDELPAY_DEBUG; 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'); } $address = ((isset($order['details']['ST'])) ? $order['details']['ST'] : $order['details']['BT']); if (!class_exists ('TableVendors')) { require(JPATH_VM_ADMINISTRATOR . DS . 'table' . DS . 'vendors.php'); } $vendorModel = VmModel::getModel ('Vendor'); $vendorModel->setId (1); $vendor = $vendorModel->getVendor (); $vendorModel->addImages ($vendor, 1); $this->getPaymentCurrency ($method); $currency_code_3 = shopFunctions::getCurrencyByID ($method->payment_currency, 'currency_code_3'); $paymentCurrency = CurrencyDisplay::getInstance ($method->payment_currency); $totalInPaymentCurrency = round ($paymentCurrency->convertCurrencyTo ($method->payment_currency, $order['details']['BT']->order_total, FALSE), 2); $cd = CurrencyDisplay::getInstance ($cart->pricesCurrency); // prepare the post var values: $languageTag = $this->getLang (); $params = array(); $params['PRESENTATION.AMOUNT'] = $totalInPaymentCurrency; $params['PRESENTATION.CURRENCY'] = $currency_code_3; $params['FRONTEND.LANGUAGE'] = $languageTag; $params['CRITERION.LANG'] = $params['FRONTEND.LANGUAGE']; $params['IDENTIFICATION.TRANSACTIONID'] = $order['details']['BT']->order_number; /* * Set payment methode to PA for online transfer, invoice and prepayment */ $PaymentTypePA = array('OT', 'PP', 'IV'); if (in_array (substr ($method->HEIDELPAY_PAYMENT_TYPE, 0, 2), $PaymentTypePA)) { $method->HEIDELPAY_PAYMENT_METHOD = "PA"; } else { $method->HEIDELPAY_PAYMENT_METHOD = $method->HEIDELPAY_PAYMENT_METHOD; } $params['PAYMENT.CODE'] = substr ($method->HEIDELPAY_PAYMENT_TYPE, 0, 2) . "." . $method->HEIDELPAY_PAYMENT_METHOD; $params['TRANSACTION.CHANNEL'] = $method->HEIDELPAY_CHANNEL_ID; /* * Special case for paypal without hco iframe */ if ($method->HEIDELPAY_PAYMENT_TYPE == "VAPAYPAL") { $params['PAYMENT.CODE'] = "VA.DB"; $params['ACCOUNT.BRAND'] = "PAYPAL"; $params['FRONTEND.PM.DEFAULT_DISABLE_ALL'] = "true"; $params['FRONTEND.PM.0.ENABLED'] = "true"; $params['FRONTEND.PM.0.METHOD'] = "VA"; $params['FRONTEND.PM.0.SUBTYPES'] = "PAYPAL"; } /* * Special case for MangirKart without hco iframe */ if ($method->HEIDELPAY_PAYMENT_TYPE == "PCMANGIR") { $params['PAYMENT.CODE'] = "PC.PA"; $params['ACCOUNT.BRAND'] = "MANGIRKART"; } /* * Special case for BarPay without hco iframe */ if ($method->HEIDELPAY_PAYMENT_TYPE == "PPBARPAY") { $params['PAYMENT.CODE'] = "PP.PA"; $params['ACCOUNT.BRAND'] = "BARPAY"; } /* * User account information */ $params['ACCOUNT.HOLDER'] = $address->first_name . " " . $address->last_name; $params['NAME.GIVEN'] = $address->first_name; $params['NAME.FAMILY'] = $address->last_name; if(!empty($address->company)) $params['NAME.COMPANY'] = $address->company ; $params['ADDRESS.STREET'] = $address->address_1; isset($address->address_2) ? $params['ADDRESS.STREET'] .= " " . $address->address_2 : ''; $params['ADDRESS.ZIP'] = $address->zip; $params['ADDRESS.CITY'] = $address->city; $params['ADDRESS.COUNTRY'] = ShopFunctions::getCountryByID ($address->virtuemart_country_id, 'country_2_code'); $params['CONTACT.EMAIL'] = $order['details']['BT']->email; $params['CONTACT.IP'] = $_SERVER['REMOTE_ADDR']; /* * Add debug informations for merchiant support */ $params['SHOP.TYPE'] = 'VirtueMart2.0.26d'; $params['SHOPMODUL.VERSION'] = $this->version; $params['CRITERION.PAYMENT_NAME'] = JText::_ ('VMPAYMENT_HEIDELPAY_' . $method->HEIDELPAY_PAYMENT_TYPE); $params['CRITERION.PAYMENT_NAME'] = strip_tags($params['CRITERION.PAYMENT_NAME']); /* * Create hash to secure the response */ $params['CRITERION.SECRET'] = $this->createSecretHash ($order['details']['BT']->order_number, $method->HEIDELPAY_SECRET); /* * Set transaction mode */ if ($method->HEIDELPAY_TRANSACTION_MODE == 2) { $params['TRANSACTION.MODE'] = "LIVE"; } elseif ($method->HEIDELPAY_TRANSACTION_MODE == 0) { $params['TRANSACTION.MODE'] = "INTEGRATOR_TEST"; } else { $params['TRANSACTION.MODE'] = "CONNECTOR_TEST"; } /* * Default configuration for hco */ $params['FRONTEND.MODE'] = "DEFAULT"; $params['FRONTEND.ENABLED'] = "true"; $params['FRONTEND.POPUP'] = "false"; $params['FRONTEND.REDIRECT_TIME'] = "0"; $params['REQUEST.VERSION'] = "1.0"; $params['FRONTEND.NEXTTARGET'] = "top.location.href"; /* * Add response and css path */ $params['FRONTEND.RESPONSE_URL'] = JROUTE::_ (JURI::root(), $xhtml=true, $ssl=0) . 'plugins/vmpayment/heidelpay/heidelpay/heidelpay_response.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived&on=' . urlencode($order['details']['BT']->order_number) . '&pm=' . $order['details']['BT']->virtuemart_paymentmethod_id; $cssFile = "heidelpay_default.css"; if (!empty($method->HEIDELPAY_STYLE)) { $cssFile = $method->HEIDELPAY_STYLE ; } $params['FRONTEND.CSS_PATH'] = JROUTE::_ (JURI::root(), $xhtml=true, $ssl=0) . 'plugins/vmpayment/heidelpay/heidelpay/' . $cssFile; $requestUrl = $method->HEIDELPAY_PAYMENT_URL; $params['SECURITY.SENDER'] = $method->HEIDELPAY_SECURITY_SENDER; $params['USER.LOGIN'] = $method->HEIDELPAY_USER_LOGIN; $params['USER.PWD'] = $method->HEIDELPAY_USER_PW; if(substr ($method->HEIDELPAY_PAYMENT_TYPE, 0, 2) == 'DD') { $sepaform = array(); $sepaform = $this->switchDirectDebitFrom($method->HEIDELPAY_SEPA_FORM); $params = array_merge($sepaform , $params); } /* * send request to payment server */ $response = $this->doRequest ($requestUrl, $params, $method->HEIDELPAY_DEBUG); if ($params['TRANSACTION.MODE'] != "LIVE") { vmInfo('VMPAYMENT_HEIDELPAY_PAYMENT_TESTMODE'); } /* * On success show iframe or show error information for your customer */ $returnValue = 0; if ($response['PROCESSING_RESULT'] == "ACK" || $response['POST_VALIDATION'] == "ACK") { $returnValue = 2; $html = $this->renderByLayout ('displaypayment', array( 'response' => $response['FRONTEND_REDIRECT_URL'] )); } else { $html = JText::_ ('VMPAYMENT_HEIDELPAY_TECHNICAL_ERROR') . "
- " . addslashes ($response[PROCESSING_RETURN]) . "
" . JText::_ ('VMPAYMENT_HEIDELPAY_CONTACT_SHOPOWNER'); } /* * Show debug information */ if ($method->HEIDELPAY_DEBUG == 1) { vmDebug('HEIDELPAY plgVmConfirmedOrder', $params); } return $this->processConfirmedOrderPaymentResponse ($returnValue, $cart, $order, $html, '', ''); } 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; } $this->getPaymentCurrency ($method); $paymentCurrencyId = $method->payment_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'); } $virtuemart_paymentmethod_id = JRequest::getInt ('pm', 0); $order_number = JRequest::getString ('on', 0); if (!($method = $this->getVmPluginMethod ($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement ($method->payment_element)) { return NULL; } if (!($virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber ($order_number))) { return NULL; } $db = JFactory::getDBO (); $_q = 'SELECT * FROM `' . $this->_tablename . '` ' . 'WHERE `virtuemart_order_id` = ' . $virtuemart_order_id; $db->setQuery ($_q); if (!($paymentData = $db->loadObject ())) { // JError::raiseWarning(500, $db->getErrorMsg()); } vmdebug ('HEIDELPAY paymentdata', $paymentData); $cart = VirtueMartCart::getCart (); $cart->emptyCart (); if ($paymentData->processing_result == "NOK") { vmError ('VMPAYMENT_HEIDELPAY_PAYMENT_FAILED','VMPAYMENT_HEIDELPAY_PAYMENT_FAILED'); vmError (" - " . $paymentData->comment," - " . $paymentData->comment); } else { vmInfo ('VMPAYMENT_HEIDELPAY_PAYMENT_SUCESS'); $html = "

".JText::sprintf ('VMPAYMENT_HEIDELPAY_ORDER_NR') . ': ' . $order_number . "

" ; $tmpkom = preg_replace("/\(-/", 'Barcode runterladen', $tmpkom ); $html .= $tmpkom; } // if payment is in test mode if ($paymentData->transaction_mode != "LIVE") { vmInfo('VMPAYMENT_HEIDELPAY_PAYMENT_TESTMODE'); } $orgSecret = $this->createSecretHash ($order_number, $method->HEIDELPAY_SECRET); $order['comments']=""; if ($virtuemart_order_id) { $order['customer_notified'] = 0; $order['order_status'] = $this->getStatus ($method, $paymentData->processing_result); $modelOrder = VmModel::getModel ('orders'); $orderitems = $modelOrder->getOrder ($virtuemart_order_id); $nb_history = count ($orderitems['history']); if ($orderitems['history'][$nb_history - 1]->order_status_code != $order['order_status']) { if ($method->HEIDELPAY_CONFIRM_EMAIL == 1 or ($method->HEIDELPAY_CONFIRM_EMAIL == 2 and $paymentData->processing_result == "ACK")) { $order['customer_notified'] = 1; $order['comments'] = JText::sprintf ('VMPAYMENT_HEIDELPAY_EMAIL_SENT') . "
"; } $order['comments'] .= $paymentData->comment; /* * Verify Payment response */ if ($orgSecret != $paymentData->secret_hash) { $order['customer_notified'] = 0; $order['comments'] = "Hash verification error, suspecting manipulation. IP: " . $paymentData->response_ip; $order['order_status'] = ''; } $modelOrder->updateStatusForOneOrder ($virtuemart_order_id, $order, TRUE); } } return TRUE; } function plgVmOnUserPaymentCancel () { if (!class_exists ('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $order_number = JRequest::getVar ('on'); if (!$order_number) { return FALSE; } $db = JFactory::getDBO (); $query = 'SELECT ' . $this->_tablename . '.`virtuemart_order_id` FROM ' . $this->_tablename . " WHERE `order_number`= '" . $order_number . "'"; $db->setQuery ($query); $virtuemart_order_id = $db->loadResult (); if (!$virtuemart_order_id) { return NULL; } return TRUE; } function getStatus ($method, $status) { if ($status == 'ACK') { $new_status = $method->HEIDELPAY_STATUS_SUCCESS; } else { $new_status = $method->HEIDELPAY_STATUS_FAILED; } return $new_status; } function plgVmOnStoreInstallPaymentPluginTable ($jplugin_id) { return $this->onStoreInstallPluginTable ($jplugin_id); } public function plgVmOnSelectCheckPayment (VirtueMartCart $cart, &$msg) { return $this->OnSelectCheck ($cart); } public function plgVmDisplayListFEPayment (VirtueMartCart $cart, $selected = 0, &$htmlIn) { return $this->displayListFE ($cart, $selected, $htmlIn); } public function plgVmonSelectedCalculatePricePayment (VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) { return $this->onSelectedCalculatePrice ($cart, $cart_prices, $cart_prices_name); } function plgVmOnCheckAutomaticSelectedPayment (VirtueMartCart $cart, array $cart_prices = array()) { return $this->onCheckAutomaticSelected ($cart, $cart_prices); } public function plgVmOnShowOrderFEPayment ($virtuemart_order_id, $virtuemart_paymentmethod_id, &$payment_name) { $this->onShowOrderFE ($virtuemart_order_id, $virtuemart_paymentmethod_id, $payment_name); } 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); } public function plgVmOnUpdateOrderPayment ($_formData) { return NULL; } public function plgVmOnUpdateOrderLine ($_formData) { return NULL; } public function plgVmOnEditOrderLineBE ($_orderId, $_lineId) { return NULL; } public function plgVmOnShowOrderLineFE ($_orderId, $_lineId) { return NULL; } protected function getLang () { $language =& JFactory::getLanguage (); $tag = strtolower (substr ($language->get ('tag'), 0, 2)); return $tag; } private function doRequest ($url, $params, $debug) { $data = $params; $result = ""; // Erstellen des Strings für die Datenübermittlung foreach ($data AS $key => $value) { if ($this->isUTF8 ($value)) { $value = utf8_decode ($value); } $key = strtoupper ($key); $value = urlencode($value); $result .= $key. "=" . $value . "&"; } $strPOST = stripslashes ($result); // prüfen ob CURL existiert if (function_exists ('curl_init')) { $ch = curl_init (); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_HEADER, 0); curl_setopt ($ch, CURLOPT_FAILONERROR, 1); curl_setopt ($ch, CURLOPT_TIMEOUT, 60); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $strPOST); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt ($ch, CURLOPT_USERAGENT, "php ctpepost"); $this->response = curl_exec ($ch); $this->error = curl_error ($ch); curl_close ($ch); $res = $this->response; if (!$this->response && $this->error) { $msg = urlencode ('Curl Fehler'); $res = 'status=FAIL&msg=' . $this->error; } } else { $msg = urlencode ('Curl Fehler'); $res = 'status=FAIL&&msg=' . $msg; } $result = NULL; parse_str ($res, $result); /* * Show debug information */ if ($debug == 1) { vmdebug ('Heildepay Response', $result); } return $result; } private function isUTF8 ($string) /*{{{*/ { if (is_array ($string)) { $enc = implode ('', $string); return @!((ord ($enc[0]) != 239) && (ord ($enc[1]) != 187) && (ord ($enc[2]) != 191)); } else { return (utf8_encode (utf8_decode ($string)) == $string); } } protected function checkConditions ($cart, $method, $cart_prices) { $address = (($cart->ST == 0) ? $cart->BT : $cart->ST); $amount = $cart_prices['salesPrice']; $amount_cond = ($amount >= $method->min_amount AND $amount <= $method->max_amount OR ($method->min_amount <= $amount AND ($method->max_amount == 0))); $countries = array(); if (!empty($method->countries)) { if (!is_array ($method->countries)) { $countries[0] = $method->countries; } else { $countries = $method->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; } function createSecretHash ($orderID, $secret) { $hash = sha1 ($orderID . $secret); return $hash; } /** * methode to change the form fields of the hco(iframe) * nessuccary for support of SEPA (single euro payments area) * @param int $mode_id id to set version * @return array parameter for hco call */ public function switchDirectDebitFrom($mode_id) { $params = array(); switch ($mode_id){ // account and bank no: case 1: $params['FRONTEND.SEPA'] = 'NO'; $params['FRONTEND.SEPASWITCH'] = 'NO'; break; // both methodes separeted with an or case 3: $params['FRONTEND.SEPA'] = 'YES'; $params['FRONTEND.SEPASWITCH'] = 'YES'; break; // both methodes with a selector case 4: $params['FRONTEND.SEPA'] = 'NO'; $params['FRONTEND.SEPASWITCH'] = 'YES'; break; // IBAN and BIC default: $params['FRONTEND.SEPA'] = 'YES'; $params['FRONTEND.SEPASWITCH'] = 'NO'; } return $params; } } heidelpay/heidelpay.xml000066600000021550151372777310011222 0ustar00 VMPAYMENT_HEIDELPAY 12-Sep-2012 Heidelberger Payment GmbH info@heidelpay.de http://www.heidelpay.de Copyright Heidelberger Payment GmbH http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL 13.11 Virtuemart Plugin von:

]]>
de-DE.plg_vmpayment_heidelpay.ini en-GB.plg_vmpayment_heidelpay.ini en-GB.plg_vmpayment_heidelpay.sys.ini heidelpay.php index.html heidelpay http://testshops.heidelpay.de/downloads/plg_vm_heidelpay.xml
heidelpay/heidelpay/heidelpay_default.css000066600000003543151372777310014664 0ustar00html,body { background-color: #ffffff; color: #00000; } tr#notMandatoryRow, tr#addressBlock, tr#userInfoBlock, tr#contactBlock, tr#spacer1, tr#spacer2, tr#spacer3, tr#spacer4 { display: none; } .frm_box { border-style: solid; border-color: #DDD; border-width:1px; background-color: #EEEEEE; } input,select { color: #000000; background-color: #ffffff; } a:link { color:#000000; } a:visited { color:#000000; } a:hover { color:#000000; } a:active { color:#000000; } a:focus { color:#000000; } .bar{ display: none; } select#paymentMethod{ display: none; } #paymentSelection{ display: none; } td.buttonRight { width : 100%; } input#send, input#continue{font-size:12px;font-weight:700;display:inline-block;text-decoration:none;color:#777;} input#send, input#continue{background:#e8e8e8 url(http://testshops.heidelpay.de/Virtuemart/backgrounds.png) top repeat-x;background-position:0 -160px;color:#fff;border:solid #00a000 1px;border-radius:4px;-webkit-border-radius:4px;-moz-border-radius:4px;font-size:12px;cursor:pointer;text-align:center;letter-spacing:1px;display:inline-block;text-decoration:none;padding:6px 12px 3px;} input#send:hover, input#continue:hover{background-position:0 -200px;color:#f2f2f2;text-decoration:none;} input#cancel, input.btn{background:#e8e8e8 url(http://testshops.heidelpay.de/Virtuemart/backgrounds.png) top repeat-x;border:solid #CAC9C9 1px;border-radius:4px;-webkit-border-radius:4px;-moz-border-radius:4px;color:#777;text-decoration:none;padding:5px 5px 4px;} input#cancel:hover, input.btn:hover{background:#e8e8e8 url(../images/vmgeneral/backgrounds.png) repeat-x;background-position:0 -40px;color:#000;text-decoration:none;} input#cancel, input.btn{display:inline-block;cursor:pointer;padding:5px 8px 4px;} input#cancel:hover, input.btn:hover{color:#777;} heidelpay/heidelpay/elements/.htaccess000066600000000177151372777310014114 0ustar00 Order allow,deny Deny from all heidelpay/heidelpay/elements/index.html000066600000000037151372777310014306 0ustar00 heidelpay/heidelpay/elements/getheidelpay.php000066600000006272151372777310015475 0ustar00 '; $doc = JFactory::getDocument (); $doc->addScriptDeclaration ($js); $cid = jrequest::getvar ('cid', NULL, 'array'); if (is_Array ($cid)) { $virtuemart_paymentmethod_id = $cid[0]; } else { $virtuemart_paymentmethod_id = $cid; } $query = "SELECT payment_params FROM `#__virtuemart_paymentmethods` WHERE virtuemart_paymentmethod_id = '" . $virtuemart_paymentmethod_id . "'"; $db = JFactory::getDBO (); $db->setQuery ($query); $params = $db->loadResult (); $payment_params = explode ("|", $params); foreach ($payment_params as $payment_param) { if (empty($payment_param)) { continue; } $param = explode ('=', $payment_param); $payment_params[$param[0]] = substr ($param[1], 1, -1); } $id=""; if ($payment_params['HEIDELPAY_SECURITY_SENDER'] == '31HA07BC8124AD82A9E96D9A35FAFD2A' or $payment_params['HEIDELPAY_SECURITY_SENDER'] == '') { $id = "heidelpay_getheidelpay_link"; $display=''; $html = '' . JText::_ ('VMPAYMENT_HEIDELPAY_ALREADY_ACCOUNT') . ''; } else { $id = "heidelpay_getheidelpay_link"; $display=' style="display: none;"'; $html = '' . JText::_ ('VMPAYMENT_HEIDELPAY_CREATE_ACCOUNT') . ''; } $lang = $this->getLang (); $html .= '
'; $url = "http://demoshops.heidelpay.de/contactform/?campaign=vituemart&shop=vituemart&lang=" . $lang; $html .= ''; $html .= "
"; return $html; } protected function getLang () { $language =& JFactory::getLanguage (); $tag = strtolower (substr ($language->get ('tag'), 0, 2)); return $tag; } }heidelpay/heidelpay/tmpl/index.html000066600000000057151372777310013450 0ustar00 heidelpay/heidelpay/tmpl/.htaccess000066600000000177151372777310013254 0ustar00 Order allow,deny Deny from all heidelpay/heidelpay/tmpl/displaypayment.php000066600000001454151372777310015231 0ustar00 * @package VirtueMart * @copyright Copyright (c) 2004 - 2012 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ ?> heidelpay/heidelpay/index.html000066600000000040151372777310012464 0ustar00 heidelpay/heidelpay/heidelpay_response.php000066600000013447151372777310015101 0ustar00 * @version 13.07 * @package VirtueMart * @subpackage payment * @copyright Copyright (C) Heidelberger Payment GmbH * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php */ include('../../../../configuration.php'); $config = new JConfig(); //echo $config->password ; foreach ($_POST as $key => $value) { $key = preg_replace('/_x$/', '', trim($key)); $_POST[$key] = $value; } foreach ($_GET as $key => $value) { $key = preg_replace('/_x$/', '', trim($key)); $_GET[$key] = $value; } if ( $_SERVER['SERVER_PORT'] == "443" ) { $Protocol = "https://"; } else { $Protocol = "http://"; } $PATH = preg_replace('@plugins\/vmpayment\/heidelpay\/heidelpay\/heidelpay_response\.php@','', $_SERVER['SCRIPT_NAME']); $URL = $_SERVER['HTTP_HOST'] . $PATH ; $redirectURL = $Protocol.$URL.'index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived&on='.$_GET['on'].'&pm='.$_GET['pm'].'&Itemid='.$_GET['Itemid']; $cancelURL = $Protocol.$URL.'index.php?option=com_virtuemart&view=pluginresponse&task=pluginUserPaymentCancel&on='.$_GET['on'].'&pm='.$_GET['pm'].'&Itemid='.$_GET['Itemid']; function updateHeidelpay($orderID, $connect) { $comment=""; if ( preg_match('/^[A-Za-z0-9 -]+$/', $orderID , $str)) { $link = mysql_connect($connect->host, $connect->user , $connect->password); mysql_select_db($connect->db); $result = mysql_query("SELECT virtuemart_order_id FROM ".$connect->dbprefix."virtuemart_orders"." WHERE order_number = '".mysql_real_escape_string($orderID)."';"); $row = mysql_fetch_object($result); $paymentCode = explode('.' , $_POST['PAYMENT_CODE']); if ($_POST['PROCESSING_RESULT'] == "NOK") { $comment = $_POST['PROCESSING_RETURN']; } elseif ($paymentCode[0] == "PP" or $paymentCode[0] == "IV") { if (strtoupper ($_POST['CRITERION_LANG']) == 'DE') { $comment = 'Bitte überweisen Sie uns den Betrag von '.$_POST['CLEARING_CURRENCY'].' '.$_POST['PRESENTATION_AMOUNT'].' auf folgendes Konto:

Land : '.$_POST['CONNECTOR_ACCOUNT_COUNTRY'].'
Kontoinhaber : '.$_POST['CONNECTOR_ACCOUNT_HOLDER'].'
Konto-Nr. : '.$_POST['CONNECTOR_ACCOUNT_NUMBER'].'
Bankleitzahl: '.$_POST['CONNECTOR_ACCOUNT_BANK'].'
IBAN: '.$_POST['CONNECTOR_ACCOUNT_IBAN'].'
BIC: '.$_POST['CONNECTOR_ACCOUNT_BIC'].'

Geben sie bitte im Verwendungszweck UNBEDINGT die Identifikationsnummer
'.$_POST['IDENTIFICATION_SHORTID'].'
und NICHTS ANDERES an.

'; } else { $comment = 'Please transfer the amount of '.$_POST['CLEARING_CURRENCY'].' '.$_POST['PRESENTATION_AMOUNT'].' to the following account:

Country: '.$_POST['CONNECTOR_ACCOUNT_COUNTRY'].'
Account holder: '.$_POST['CONNECTOR_ACCOUNT_HOLDER'].'
Account No.: '.$_POST['CONNECTOR_ACCOUNT_NUMBER'].'
Bank Code: '.$_POST['CONNECTOR_ACCOUNT_BANK'].'
IBAN: '.$_POST['CONNECTOR_ACCOUNT_IBAN'].'
BIC: '.$_POST['CONNECTOR_ACCOUNT_BIC'].'

When you transfer the money you HAVE TO use the identification number
'.$_POST['IDENTIFICATION_SHORTID'].'
as the descriptor and nothing else. Otherwise we cannot match your transaction!

'; } if($_POST['ACCOUNT_BRAND'] == 'BARPAY') { $comment = '(-'.$_POST['CRITERION_BARPAY_PAYCODE_URL'].'-)

Drucken Sie den Barcode aus oder speichern Sie diesen auf Ihrem mobilen Endger�t. Gehen Sie nun zu einer Kasse der 18.000 Akzeptanzstellen in Deutschland und bezahlen Sie ganz einfach in bar. In dem Augenblick, wenn der Rechnungsbetrag beglichen wird, erh�lt der Online-H�ndler die Information �ber den Zahlungseingang.Die bestellte Ware oder Dienstleistung geht umgehend in den Versand '; } } if (!empty($row->virtuemart_order_id)) { $sql = "INSERT ".$connect->dbprefix."virtuemart_payment_plg_heidelpay SET " . "virtuemart_order_id = \"".mysql_real_escape_string($row->virtuemart_order_id). "\"," . "order_number = \"".mysql_real_escape_string($_GET['on']). "\"," . "virtuemart_paymentmethod_id = \"".mysql_real_escape_string($_GET['pm']). "\"," . "unique_id = \"".mysql_real_escape_string($_POST['IDENTIFICATION_UNIQUEID']). "\"," . "short_id = \"".mysql_real_escape_string($_POST['IDENTIFICATION_SHORTID']). "\"," . "payment_code = \"".mysql_real_escape_string($_POST['PROCESSING_REASON_CODE']). "\"," . "comment = \"".mysql_real_escape_string($comment). "\"," . "payment_methode = \"".mysql_real_escape_string($paymentCode[0]). "\"," . "payment_type = \"".mysql_real_escape_string($paymentCode[1]). "\"," . "transaction_mode = \"".mysql_real_escape_string($_POST['TRANSACTION_MODE']). "\"," . "payment_name = \"".mysql_real_escape_string($_POST['CRITERION_PAYMENT_NAME']). "\"," . "processing_result = \"".mysql_real_escape_string($_POST['PROCESSING_RESULT']). "\"," . "secret_hash = \"".mysql_real_escape_string($_POST['CRITERION_SECRET']). "\"," . "response_ip = \"".mysql_real_escape_string($_SERVER['REMOTE_ADDR']). "\";" ; $dbEerror = mysql_query($sql); } } } $returnvalue=$_POST['PROCESSING_RESULT']; if (!empty($returnvalue)){ if (strstr($returnvalue,"ACK")) { print $redirectURL; updateHeidelpay($_POST['IDENTIFICATION_TRANSACTIONID'], $config); } else if ($_POST['FRONTEND_REQUEST_CANCELLED'] == 'true'){ print $cancelURL ; } else { updateHeidelpay($_POST['IDENTIFICATION_TRANSACTIONID'], $config); print $redirectURL; } } else { echo 'FAIL'; } ?> heidelpay/heidelpay/.htaccess000066600000000177151372777310012300 0ustar00 Order allow,deny Deny from all heidelpay/.htaccess000066600000000177151372777310010334 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout.xml000066600000012607151372777310013311 0ustar00 Klarna Checkout January 10 2014 The VirtueMart Development Team http://www.virtuemart.net Copyright (C) 2004-2014 Virtuemart Team. All rights reserved. http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL 2.0.26d klarnacheckout.php /> klarnacheckout/klarnacheckout.php000066600000164205151372777310013302 0ustar00_loggable = TRUE; $this->tableFields = array_keys($this->getTableSQLFields()); $this->_tablepkey = 'id'; //virtuemart_sofort_id'; $this->_tableId = 'id'; //'virtuemart_sofort_id'; $varsToPush = $this->getVarsToPush(); $this->setConfigParameterable($this->_configTableFieldName, $varsToPush); plgVmPaymentKlarnaCheckout::includeKlarnaFiles(); } /** * @return string */ public function getVmPluginCreateTableSQL () { return $this->createTableSQL('Payment KlarnaCheckout 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(1000)', 'action' => 'varchar(20)', // to_klarna, from_klarna 'klarna_status' => 'varchar(20)', // pre-purchase, purchase, pre-delivery, delivery, post-delivery 'data' => 'text', // what was sent ); return $SQLfields; } /** * This shows the plugin for choosing in the payment list of the checkout process. * * @author Valerie Cartan Isaksen */ 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; } } $htmla = array(); $html = ''; VmConfig::loadJLang('com_virtuemart'); $currency = CurrencyDisplay::getInstance(); $showallform=true; foreach ($this->methods as $method) { if ($this->checkConditions($cart, $method, $cart->pricesUnformatted)) { $methodSalesPrice = $this->calculateSalesPrice($cart, $method, $cart->pricesUnformatted); if (!empty($method->payment_logos)) { $logo = ''; } $payment_cost = ''; if ($methodSalesPrice) { $payment_cost = $currency->priceDisplay($methodSalesPrice); } if ($selected == $method->virtuemart_paymentmethod_id) { $checked = 'checked="checked"'; } else { $checked = ''; } if ($cart->virtuemart_paymentmethod_id == $method->virtuemart_paymentmethod_id) { $showallform=false; } $html = $this->renderByLayout('display_payment', array( 'plugin' => $method, 'checked' => $checked, 'payment_logo' => $logo, 'payment_cost' => $payment_cost, 'showallform' => $showallform )); $htmla[] = $html; } } if ( $showallform) { $js = ' jQuery(document).ready(function( $ ) { $("#checkoutForm").show(); $(".billto-shipto").show(); $("#com-form-login").show(); }); '; $document = JFactory::getDocument(); $document->addScriptDeclaration ( $js); } if (!empty($htmla)) { $htmlIn[] = $htmla; } return true; } function getCartItems ($cart) { vmdebug('getProductItems', $cart->pricesUnformatted); //self::includeKlarnaFiles(); $i = 0; foreach ($cart->products as $pkey => $product) { $items[$i]['reference'] = !empty($product->sku) ? $product->sku : $product->virtuemart_product_id; $items[$i]['name'] = $product->product_name; $items[$i]['quantity'] = (int)$product->quantity; $price = !empty($product->prices['basePriceWithTax']) ? $product->prices['basePriceWithTax'] : $product->prices['basePriceVariant']; $itemInPaymentCurrency = vmPSPlugin::getAmountInCurrency($price,$this->method->payment_currency); $items[$i]['unit_price'] = round($itemInPaymentCurrency['value'] * 100, 0) ; //$items[$i]['discount_rate'] = $discountRate; // Bug indoc: discount is not supported //$items[$i]['discount'] = abs($cart->pricesUnformatted[$pkey]['discountAmount']*100); $tax_rate = round($this->getVatTaxProduct($cart->pricesUnformatted[$pkey]['VatTax']) ); $items[$i]['tax_rate'] = $tax_rate * 100; //$this->debugLog($unitPriceCentsInPaymentCurrency, 'getCartItems', 'debug'); //$this->debugLog($cart->pricesUnformatted[$pkey], 'getCartItems Products', 'debug'); $this->debugLog($items[$i], 'getCartItems', 'debug'); $i++; // ADD A DISCOUNT AS A NEGATIVE VALUE FOR THAT PRODUCT if ($cart->pricesUnformatted[$pkey]['discountAmount'] != 0.0) { $items[$i]['reference'] = $items[$i-1]['reference']; $items[$i]['name'] = $items[$i-1]['name']. ' ('.JText::_('VMPAYMENT_KLARNACHECKOUT_PRODUCTDISCOUNT'). ')'; $items[$i]['quantity'] =(int)$product->quantity; $discount_tax_percent=0.0; $discountInPaymentCurrency = vmPSPlugin::getAmountInCurrency(abs($cart->pricesUnformatted[$pkey]['discountAmount']),$this->method->payment_currency); $discountAmount=- abs( round($discountInPaymentCurrency['value'] * 100 , 0)); if ($cart->pricesUnformatted[$pkey]['discountAmount'] > 0.0) { $items[$i]['tax_rate'] =$items[$i-1]['tax_rate']; } else { $items[$i]['tax_rate'] =0.0; $tax_rate =0.0; } $items[$i]['unit_price'] = round($discountAmount * (1+ ($tax_rate*0.01)) , 0); $this->debugLog($items[$i], 'getCartItems', 'debug'); $i++; } } if ($cart->pricesUnformatted['salesPriceCoupon']) { $items[$i]['reference'] = 'COUPON'; $items[$i]['name'] = 'Coupon discount'; $items[$i]['quantity'] = 1; $couponInPaymentCurrency = vmPSPlugin::getAmountInCurrency($cart->pricesUnformatted['salesPriceCoupon'],$this->method->payment_currency); $items[$i]['unit_price'] = round( $couponInPaymentCurrency['value'] *100, 0); $items[$i]['tax_rate'] = 0; $this->debugLog($cart->pricesUnformatted['salesPriceCoupon'], 'getCartItems Coupon', 'debug'); $this->debugLog($items[$i], 'getCartItems', 'debug'); $i++; } if ($cart->pricesUnformatted['salesPriceShipment']) { $items[$i]['reference'] = 'SHIPPING'; $items[$i]['name'] = 'Shipping Fee'; $items[$i]['quantity'] = 1; $shipmentInPaymentCurrency = vmPSPlugin::getAmountInCurrency($cart->pricesUnformatted['salesPriceShipment'],$this->method->payment_currency); $items[$i]['unit_price'] = round( $shipmentInPaymentCurrency['value'] *100, 0); $items[$i]['tax_rate'] = $this->getTaxShipment($cart->pricesUnformatted['shipment_calc_id']); $this->debugLog($cart->pricesUnformatted['salesPriceShipment'], 'getCartItems Shipment', 'debug'); $this->debugLog($items[$i], 'getCartItems', 'debug'); } $currency = CurrencyDisplay::getInstance($cart->paymentCurrency); return $items; } function getTaxShipment ($shipment_calc_id) { // TO DO add shipmentTaxRate in the cart // assuming there is only one rule +% $db = JFactory::getDBO(); $q = 'SELECT * FROM #__virtuemart_calcs WHERE `virtuemart_calc_id`="' . $shipment_calc_id . '" '; $db->setQuery($q); $taxrule = $db->loadObject(); if ($taxrule->calc_value_mathop != "+%") { VmError('KlarnaCheckout getTaxShipment: expecting math operation to be +% but is ' . $taxrule->calc_value_mathop); } return $taxrule->calc_value * 100; } function getVatTaxProduct ($vatTax) { $countRules = count($vatTax); if ($countRules == 0) { return 0; } if ($countRules > 1) { VmError('KlarnaCheckout: More then one VATax for the product:' . $countRules); } $tax = current($vatTax); if ($tax[2] != "+%") { VmError('KlarnaCheckout: expecting math operation to be +% but is ' . $tax[2]); } return $tax[1]; } function plgVmOnCheckoutAdvertise ($cart, &$payment_advertise) { if ($this->getPluginMethods($cart->vendorId) === 0) { return FALSE; } $virtuemart_paymentmethod_id = 0; foreach ($this->methods as $method) { if ($cart->virtuemart_paymentmethod_id == $method->virtuemart_paymentmethod_id) { $virtuemart_paymentmethod_id = $method->virtuemart_paymentmethod_id; } } if ($virtuemart_paymentmethod_id == 0 or empty($cart->products)) { return; } if (!($this->method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } // Check if it is the same payment_method_id as the previous one. $session = JFactory::getSession(); $klarna_paymentmethod_id_active = $session->get('klarna_paymentmethod_id_active', '', 'vm'); if ($klarna_paymentmethod_id_active != $cart->virtuemart_paymentmethod_id) { $session->clear('klarna_checkout', 'vm'); $session->clear('klarna_paymentmethod_id_active', 'vm'); } $return = $this->initKlarnaParams($this->method); if (!$return) { return; } $message = ''; $snippet = ''; $hide_BTST=true; if ($cart->virtuemart_shipmentmethod_id == 0) { $message = JText::sprintf('VMPAYMENT_KLARNACHECKOUT_SELECT_SHIPMENT_FIRST', $this->method->payment_name); } else { $session = JFactory::getSession(); $cartIdInTable = $this->storeCartInTable($cart); require_once 'klarnacheckout/library/Checkout.php'; Klarna_Checkout_Order::$baseUri = 'https://checkout.testdrive.klarna.com/checkout/orders'; Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; //session_start(); $klarna_checkout = $session->get('klarna_checkout', '', 'vm'); $connector = Klarna_Checkout_Connector::create($this->sharedsecret); $klarnaOrder = null; //if (array_key_exists('klarna_checkout', $_SESSION)) { if (!empty($klarna_checkout)) { // Resume session $klarnaOrder = new Klarna_Checkout_Order($connector, $klarna_checkout); try { $klarnaOrder->fetch(); // Reset cart $update['cart']['items'] = array(); $update['cart']['items'] = $this->getCartItems($cart ); if (!empty( $cart->BT['email'])) { $update['shipping_address']['email'] = $cart->BT['email']; $hide_BTST=false; $address = (($cart->ST == 0) ? $cart->BT : $cart->ST); if (isset($address['zip']) and !empty($address['zip'])) { $update['shipping_address']['postal_code'] = $cart->BT['zip']; } } $klarnaOrder->update($update); $this->debugLog($update, 'plgVmOnCheckoutAdvertise update', 'debug'); } catch (Exception $e) { // Reset session $klarnaOrder = null; //unset($_SESSION['klarna_checkout']); $session->clear('klarna_checkout', 'vm'); $session->clear('klarna_paymentmethod_id_active', 'vm'); } } if ($klarnaOrder == null) { // Start new session $create['purchase_country'] = $this->country_code_2; $create['purchase_currency'] = $this->currency_code_3; $create['locale'] = $this->locale; $create['merchant']['id'] = $this->merchantid; $create['merchant']['terms_uri'] = $this->getTermsURI($cart->vendorId); $create['merchant']['checkout_uri'] = JURI::root(). 'index.php?option=com_virtuemart&view=cart'; $create['merchant']['confirmation_uri'] = JURI::root().'index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived&t&pm=' . $virtuemart_paymentmethod_id . '&cartId=' . $cartIdInTable . '&klarna_order={checkout.order.uri}'; // You can not receive push notification on non publicly available uri $create['merchant']['push_uri'] = JURI::root().'index.php?option=com_virtuemart&view=pluginresponse&task=pluginnotification&tmpl=component&pm=' . $virtuemart_paymentmethod_id . '&cartId=' . $cartIdInTable . '&klarna_order={checkout.order.uri}'; if (!empty( $cart->BT['email'])) { $create['shipping_address']['email'] = $cart->BT['email']; $hide_BTST=false; $address = (($cart->ST == 0) ? $cart->BT : $cart->ST); if (isset($address['zip']) and !empty($address['zip'])) { $create['shipping_address']['postal_code'] = $cart->BT['zip']; } } $create['cart']['items'] = $this->getCartItems($cart, $method); try { $klarnaOrder = new Klarna_Checkout_Order($connector); $klarnaOrder->create($create); $klarnaOrder->fetch(); $this->debugLog($create, 'plgVmOnCheckoutAdvertise create', 'debug'); } catch (Exception $e) { $session->clear('klarna_checkout', 'vm'); $session->clear('klarna_paymentmethod_id_active', 'vm'); $admin_msg = $e->getMessage(); vmError($admin_msg, JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $method->payment_name)); $this->debugLog($admin_msg, 'plgVmOnCheckoutAdvertise', 'error'); $this->debugLog($create, 'plgVmOnCheckoutAdvertise', 'error'); return NULL; } } // Store location of checkout session //$_SESSION['klarna_checkout'] = $sessionId = $order->getLocation(); $session->set('klarna_checkout', $klarnaOrder->getLocation(), 'vm'); $session->set('klarna_paymentmethod_id_active', $virtuemart_paymentmethod_id, 'vm'); // Display checkout $snippet = $klarnaOrder['gui']['snippet']; // DESKTOP: Width of containing block shall be at least 750px // MOBILE: Width of containing block shall be 100% of browser window (No // padding or margin) } $payment_advertise[] = $this->renderByLayout('cart_advertisement', array( 'snippet' => $snippet, 'message' => $message, 'hide_BTST' => $hide_BTST, )); } /** * cf https://docs.klarna.com/en/rest-api#supported_locales * @param $method */ function initKlarnaParams ($method) { $return = true; $db = JFactory::getDBO(); $q = 'SELECT ' . $db->getEscaped('country_2_code') . ' , ' . $db->getEscaped('country_3_code') . ' FROM `#__virtuemart_countries` WHERE virtuemart_country_id = ' . (int)$method->purchase_country; $db->setQuery($q); $country = $db->loadObject(); if (!$country) { vmError('Klarna Checkout: No country has been found with country id=' . $method->purchase_country, JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $method->payment_name)); $this->debugLog('No country has been found with country id=' . $method->purchase_country, 'initKlarnaParams', 'error'); $return = false; } $this->country_code_2 = $country->country_2_code; $this->country_code_3 = $country->country_3_code; $this->getPaymentCurrency($method); $this->currency_code_3 = shopFunctions::getCurrencyByID($method->payment_currency, 'currency_code_3'); if (!$this->currency_code_3) { vmError('Klarna Checkout: No currency has been found with currency id=' . $method->payment_currency, JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $method->payment_name)); $this->debugLog('No currency has been found with currency id=' . $method->payment_currency, 'initKlarnaParams', 'error'); $return = false; } $this->currency_id = $method->payment_currency; if (empty($method->sharedsecret) or empty($method->merchantid)) { vmError('Klarna Checkout: Missing mandatory values merchant id=' . $method->merchantid . ' shared secret=' . $method->sharedsecret, JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $method->payment_name)); $this->debugLog('Missing mandatory values merchant id=' . $method->merchantid . ' shared secret=' . $method->sharedsecret, 'initKlarnaParams', 'error'); $return = false; } $this->locale = $method->locale; $this->sharedsecret = $method->sharedsecret; $this->merchantid = $method->merchantid; if ($method->server == 'beta') { $this->mode = Klarna::BETA; } else { $this->mode = Klarna::LIVE; } $this->ssl = KlarnaHandler::getKlarnaSSL($this->mode); return $return; } function getTermsURI ($vendorId) { return JURI::root() . 'index.php?option=com_virtuemart&view=vendor&layout=tos&virtuemart_vendor_id=' . $vendorId . '&lang='.JRequest::getCmd('lang','') ;; } /** Insert or Update the cart content in the table * will be used by the push notification to retrieve the cart and save the order * @param $cart */ function storeCartInTable ($cart, $cartId = 0, $dbValues = array()) { if (empty($dbValues)) { $dbValues['order_number'] = ''; $dbValues['payment_name'] = ''; $dbValues['virtuemart_paymentmethod_id'] = $cart->virtuemart_paymentmethod_id; $dbValues['action'] = 'storeCart'; $dbValues['klarna_status'] = 'pre-purchase'; } if (empty($cartId)) { $session = JFactory::getSession(); $cartIdInTable = $session->get('cartId', 0, 'vm'); $dbValues['data'] = serialize($cart); //$dbValues['data'] = ($cart); $preload = false; } else { $cartIdInTable = $cartId; //$dbValues['data'] = $this->getCartFromTable($cartId, true); $dbValues['data'] = serialize($cart); $preload = true; } $dbValues ['id'] = $cartIdInTable; $this->debugLog($dbValues, 'storePSPluginInternalData storeCartInTable', 'debug'); //$values = $this->storePSPluginInternalData($dbValues, $this->_tablepkey, $preload); $values = $this->storePluginInternalData($dbValues, $this->_tablepkey, 0, $preload); /* //$storedcart=unserialize($dbValues['data']); $storedcart= ($dbValues['data']); if ($storedcart !== $cart) { $this->debugLog($cart, 'storeCartInTable cart', 'error'); $this->debugLog($dbValues, 'storeCartInTable dbValues', 'error'); } */ if (empty($cartId)) { $session->set('cartId', $values ['id'], 'vm'); } return $values ['id']; } /** get the cart saved in the cart table * used by the push notification to retrieve the cart and save the order * @param $cart */ function getCartFromTable ($cartId, $serialized = false) { $db = JFactory::getDBO(); $q = 'SELECT * FROM `' . $this->_tablename . '` ' . 'WHERE `id` = ' . $cartId . ' AND `action` = "storeCart"'; $db->setQuery($q); $result = $db->loadObject(); if ($serialized) { $data = $result->data; } else { $data = unserialize($result->data); //return ($result->data); } return $data; } /** get the cart saved in the cart table * used by the push notification to retrieve the cart and save the order * @param $cart */ function clearCartFromTable () { //$session = JFactory::getSession(); //$session->clear('cartId', 'vm'); /* $db = JFactory::getDBO(); $q = 'DELETE FROM ' . $db->quoteName($this->_cartTablename) . ' WHERE `session_id`=' . $db->quote($sessionId); $db->setQuery($q); $db->query(); */ } /* * @param $method plugin * @param $where from where tis function is called */ protected function renderPluginName ($method, $where = 'checkout') { $payment_logo = ""; if (!empty($method->payment_logos)) { $payment_logo = ' '; } $payment_name = $method->payment_name; $html = $this->renderByLayout('render_pluginname', array( 'where' => $where, 'logo' => $payment_logo, 'payment_name' => $payment_name, 'payment_description' => $method->payment_desc, )); return $html; } /** * This is for checking the input data of the payment method within the checkout * * @author Valerie Cartan Isaksen */ function plgVmOnCheckoutCheckDataPayment (VirtueMartCart $cart) { if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } return true; } /** * @return bool|null */ /** * @param $html * @return bool|null|string */ 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'); } require_once 'klarnacheckout/library/Checkout.php'; $virtuemart_paymentmethod_id = JRequest::getInt('pm', 0); if (!($this->method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement($this->method->payment_element)) { return NULL; } //session_start(); $session = JFactory::getSession(); Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; $this->initKlarnaParams($this->method); $connector = Klarna_Checkout_Connector::create($this->sharedsecret); //$checkoutId = $_SESSION['klarna_checkout']; $checkoutId = $session->get('klarna_checkout', 0, 'vm'); if (empty($checkoutId)) { vmError('Missing klarna_checkout in session', 'Missing klarna_checkout in session', JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); $this->debugLog('Missing klarna_checkout in session', 'plgVmOnPaymentResponseReceived', 'error'); return NULL; } $order = new Klarna_Checkout_Order($connector, $checkoutId); $order->fetch(); if ($order['status'] == 'checkout_incomplete') { $app = JFactory::getApplication(); $app->redirect(JRoute::_('index.php?option=com_virtuemart&view=cart',false), JText::_('VMPAYMENT_KLARNACHECKOUT_INCOMPLETE')); } $snippet = $order['gui']['snippet']; // DESKTOP: Width of containing block shall be at least 750px // MOBILE: Width of containing block shall be 100% of browser window (No // padding or margin) //$html .= var_export($order->_data); $html = $this->renderByLayout('response_received', array( 'snippet' => $snippet, )); //unset($_SESSION['klarna_checkout']); $session->clear('klarna_checkout', 'vm'); $session->clear('cartId', 'vm'); // let's do //We delete the old stuff // get the correct cart / session $cart = VirtueMartCart::getCart(); $cart->emptyCart(); return TRUE; } /* * plgVmOnPaymentNotification() - This event is fired by Offline Payment. It can be used to validate the payment data as entered by the user. * Return: * Parameters: * None * @author Valerie Isaksen */ /** * @return bool|null */ function plgVmOnPaymentNotification () { $virtuemart_paymentmethod_id = JRequest::getInt('pm', ''); $checkoutId = JRequest::getString('klarna_order', ''); $cartId = JRequest::getString('cartId', ''); if (empty($virtuemart_paymentmethod_id) or !$this->selectedThisByMethodId($virtuemart_paymentmethod_id) or empty($checkoutId) or empty($cartId)) { return NULL; } if (!($this->method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!($cartDataFromTable = $this->getCartFromTable($cartId))) { $this->debugLog('No cart with this Id=' . $cartId, 'plgVmOnPaymentNotification', 'error'); return NULL; // No cart with this Id } $this->debugLog('OK', 'plgVmOnPaymentNotification getCartFromTable', 'debug'); require_once 'klarnacheckout/library/Checkout.php'; Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json"; $this->initKlarnaParams($this->method); $connector = Klarna_Checkout_Connector::create($this->sharedsecret); $klarna_order = new Klarna_Checkout_Order($connector, $checkoutId); $klarna_order->fetch(); if ($klarna_order['status'] != "checkout_complete") { $this->debugLog($klarna_order, 'plgVmOnPaymentNotification Klarna_Checkout_Order', 'error'); return NULL; } // At this point make sure the order is created in your system and send a // confirmation email to the customer $vmOrderNumber = $this->createVmOrder($klarna_order, $cartDataFromTable, (int)$cartId); // update Order status $update['status'] = 'created'; $update['merchant_reference'] = array( 'orderid1' => $vmOrderNumber ); $klarna_order->update($update); if (!class_exists('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $values['virtuemart_order_id'] = VirtueMartModelOrders::getOrderIdByOrderNumber($vmOrderNumber); $dbValues = array( 'virtuemart_order_id' => VirtueMartModelOrders::getOrderIdByOrderNumber($vmOrderNumber), 'order_number' => $vmOrderNumber, 'virtuemart_paymentmethod_id' => $this->method->virtuemart_paymentmethod_id, 'payment_name' => $this->renderPluginName($this->method, 'create_order'), 'action' => 'update', 'klarna_status' => $update['status'], 'data' => serialize($update) ); $this->debugLog($dbValues, 'plgVmOnPaymentNotification update', 'debug'); //$this->storePSPluginInternalData($dbValues ); $return = $this->storePluginInternalData($dbValues, 0, 0, false); $this->debugLog($return, 'plgVmOnPaymentNotification RETURN', 'debug'); } /** * Create the VM order with the saved cart, and the users infos from klarna * @param $klarna_order return data from Klarna * @param $cartData cart unserialized saved in the table * @param $method * @param $cartId pkey of the cart saved in the table * */ function createVmOrder ($klarna_order, $cartData, $cartId) { 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'); } $cartData->_confirmDone = true; $cartData->_dataValidated = true; if (!class_exists('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart(false, array(), serialize($cartData)); $this->updateBTSTAddressInCart($cart, $klarna_order); $orderId = $cart->confirmedOrder(); $this->debugLog($orderId, 'createVmOrder', 'debug'); if (!class_exists('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $modelOrder = VmModel::getModel('orders'); $order_number = VirtueMartModelOrders::getOrderNumber($orderId); $history = array(); $history['customer_notified'] = 1; $history['order_status'] = $this->method->status_checkout_complete; $history['comments'] = JText::sprintf('VMPAYMENT_KLARNACHECKOUT_PAYMENT_STATUS_CHECKOUT_COMPLETE', $order_number); $modelOrder->updateStatusForOneOrder($orderId, $history, TRUE); $this->debugLog('', 'AFTER updateStatusForOneOrder', 'debug'); $klarna_data = $this->getKlarnaData($klarna_order); //$this->debugLog('plgVmOnPaymentNotification KLARNA DATA ' . var_export($klarna_data, true), 'message'); $order_number = VirtueMartModelOrders::getOrderNumber($orderId); $dbValues = array( 'virtuemart_order_id' => $orderId, 'order_number' => $order_number, 'virtuemart_paymentmethod_id' => $this->method->virtuemart_paymentmethod_id, 'payment_name' => $this->renderPluginName($this->method, 'create_order'), 'action' => 'createOrder', 'klarna_status' => $klarna_order['status'], //'data' => ($klarna_data), 'data' => serialize($klarna_data), ); $this->debugLog($dbValues, 'storePSPluginInternalData createVmOrder', 'debug'); $this->storePSPluginInternalData($dbValues); $dbValues = array( 'virtuemart_order_id' => $orderId, 'order_number' => VirtueMartModelOrders::getOrderNumber($orderId), 'virtuemart_paymentmethod_id' => $this->method->virtuemart_paymentmethod_id, 'payment_name' => 'Klarna Checkout', 'action' => 'storeCart', 'klarna_status' => 'pre-purchase', ); $this->storeCartInTable($cartData, $cartId, $dbValues); return $order_number; } function updateBTSTAddressInCart ($cart, $klarna_order) { $result = $this->updateAddressInCart($cart, $klarna_order['billing_address'], 'BT'); $result = $this->updateAddressInCart($cart, $klarna_order['shipping_address'], 'ST'); } function updateAddressInCart ($cart, $klarna_address, $address_type) { if ($address_type == 'BT') { $prefix = ''; $vmAddress = $cart->BT; } else { $prefix = 'shipto_'; $vmAddress = $cart->ST; } // Update the Shipping Address to what is specified in the register. $update_data = array( $prefix . 'address_type_name' => 'klarnacheckout', $prefix . 'company' => $klarna_address['company_name'], $prefix . 'first_name' => $klarna_address['given_name'], $prefix . 'last_name' => $klarna_address['family_name'], $prefix . 'address_1' => $klarna_address['street_address'], $prefix . 'zip' => $klarna_address['postal_code'], $prefix . 'city' => $klarna_address['city'], $prefix . 'virtuemart_country_id' => shopFunctions::getCountryIDByName($klarna_address['country']), $prefix . 'state' => '', $prefix . 'phone_1' => $klarna_address['phone'], 'address_type' => $address_type ); if ($address_type == 'BT') { $update_data ['email'] = $klarna_address['email']; } if (!empty($st)) { $update_data = array_merge($vmAddress, $update_data); } $cart->saveAddressInCart($update_data, $update_data['address_type'], FALSE); } function getKlarnaData ($klarna_order) { $push_params = $this->getKlarnaDisplayParams(); foreach ($push_params as $key => $value) { $klarna_data[$key] = $klarna_order[$key]; } return $klarna_data; } function getKlarnaDisplayParams () { return array( 'id' => 'debug', 'purchase_country' => 'display', 'purchase_currency' => 'display', 'locale' => 'debug', 'status' => 'display', 'reference' => 'display', 'reservation' => 'display', 'started_at' => 'debug', 'completed_at' => 'debug', 'last_modified_at' => 'debug', 'expires_at' => 'debug', 'cart' => 'debug', 'customer' => 'debug', 'shipping_address' => 'debug', 'billing_address' => 'debug', 'options' => 'debug', 'merchant' => 'debug', ); } /** * @param $virtuemart_paymentmethod_id * @param $paymentCurrencyId * @return bool|null */ function plgVmgetEmailCurrency ($virtuemart_paymentmethod_id, $virtuemart_order_id, &$emailCurrencyId) { if (!($this->method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement($this->method->payment_element)) { return FALSE; } if (!($payments = $this->getDatasByOrderId($virtuemart_order_id))) { 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; } } /** * @param $virtuemart_paymentmethod_id * @param $paymentCurrencyId * @return bool|null */ function plgVmgetPaymentCurrency ($virtuemart_paymentmethod_id, &$paymentCurrencyId) { if (!($this->method = $this->getVmPluginMethod($virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement($this->method->payment_element)) { return FALSE; } $this->getPaymentCurrency($this->method); $paymentCurrencyId = $this->method->payment_currency; } /** * Display stored payment data for an order * @param int $virtuemart_order_id * @param int $payment_method_id * @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->method = $this->getVmPluginMethod($payment_method_id))) { return NULL; // Another method was selected, do nothing } if (!($payments = $this->getDatasByOrderId($virtuemart_order_id))) { // JError::raiseWarning(500, $db->getErrorMsg()); return ''; } $html = '' . "\n"; $html .= $this->getHtmlHeaderBE(); $first = TRUE; if ($this->method->debug) { $html .= ''; } foreach ($payments as $payment) { $display_action = 'onShowOrderBE_' . $payment->action; $row_html = $this->$display_action($payment); if ($row_html) { $html .= ''; $html .= $row_html; } } $html .= '
' . JText::_('VMPAYMENT_KLARNACHECKOUT_ORDER_BE_WARNING') . '
' . JText::_('VMPAYMENT_KLARNACHECKOUT_DATE') . '' . $payment->created_on . '
' . "\n"; return $html; } function onShowOrderBE_activate ($payment) { if (!class_exists('VirtueMartModelOrders')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php'); } $html = $this->getHtmlRowBE(JText::_('VMPAYMENT_KLARNACHECKOUT_STATUS'), $payment->klarna_status); $activate_data = unserialize($payment->data); $html .= $this->getHtmlRowBE(JText::_('VMPAYMENT_KLARNACHECKOUT_INVOICE_NUMBER'), $activate_data['InvoiceNumber']); if (!empty($activate_data['InvoicePdf'])) { // get order password $orderModel = VmModel::getModel(); $virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($payment->order_number); $invoicePdfLink=$this->getInvoicePdfLink($virtuemart_order_id); $value = '' . JText::_('VMPAYMENT_KLARNACHECKOUT_VIEW_INVOICE') . ''; $html .= $this->getHtmlRowBE("", $value); } return $html; } function onShowOrderBE_update ($payment) { $html = $this->getHtmlRowBE(JText::_('VMPAYMENT_KLARNACHECKOUT_STATUS'), $payment->klarna_status); return $html; } function onShowOrderBE_cancelReservation ($payment) { return $this->getHtmlRowBE(JText::_('VMPAYMENT_KLARNACHECKOUT_STATUS'), $payment->klarna_status); } /** * @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 = jrequest::getWord('call'); $this->$call(); // jexit(); } function onShowOrderBE_createOrder ($payment) { if ($this->method->debug) { $show_fields = array("display", "debug"); } else { $show_fields = array("display"); } if (empty($payment->data)) { $html = "\n" . JText::_('id') . "\n " . 'ERROR NO DATA' . "\n\n"; } else { $klarna_order = unserialize($payment->data); //$klarna_order = ($payment->data); $push_params = $this->getKlarnaDisplayParams(); $html = ''; $lang = JFactory::getLanguage(); foreach ($push_params as $key => $value) { if (in_array($value, $show_fields)) { $display_value = isset($klarna_order[$key]) ? $klarna_order[$key] : "???"; $text_key = strtoupper('VMPAYMENT_KLARNACHECKOUT_' . $key); if ($lang->hasKey($text_key)) { $text = JText::_('VMPAYMENT_KLARNACHECKOUT_' . $key); } else { $text = $key; } if (!is_array($display_value)) { $html .= "\n" . $text . "\n " . $display_value . "\n\n"; } else { $html .= "\n" . $text . "\n \n\n"; foreach ($klarna_order[$key] as $order_key => $order_value) { $text_key = strtoupper('VMPAYMENT_KLARNACHECKOUT_' . $order_key); if ($lang->hasKey($text_key)) { $text = JText::_('VMPAYMENT_KLARNACHECKOUT_' . $order_key); } else { $text = $order_key; } if (!is_array($order_value)) { $display_order_value = isset($klarna_order[$key][$order_key]) ? $klarna_order[$key][$order_key] : "????"; $html .= "\n" . $text . "\n " . $display_order_value . "\n\n"; } else { $html .= "\n" . $text . "\n
" . var_export($klarna_order[$key][$order_key], true) . "
\n\n"; } } } } } } return $html; } /** * Can be usefull for debugging * @param $payment * @return string */ function onShowOrderBE_storeCart ($payment) { $html = ''; if ($this->method->debug) { if (!class_exists('VirtueMartCart')) { require(JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'); } $cart = VirtueMartCart::getCart(false, array(), $payment->data); $html = "\n" . JText::_('storeCart') . "\n
" . var_export($cart->products, true) . "
\n\n"; } return $html; } /** * Check if the payment conditions are fulfilled for this payment method * * @author: Valerie Isaksen * * @param $cart_prices: cart prices * @param $payment * @return true: if the conditions are fulfilled, false otherwise * */ protected function checkConditions ($cart, $method, $cart_prices) { $this->convert($method); $address = $cart->BT; $amount = $cart_prices['salesPrice']; $amount_cond = ($amount >= $method->min_amount AND $amount <= $method->max_amount OR ($method->min_amount <= $amount AND ($method->max_amount == 0))); $countries = array(); if (!empty($method->purchase_country)) { if (!is_array($method->purchase_country)) { $countries[0] = $method->purchase_country; } else { $countries = $method->purchase_country; } } // 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 ((!empty($address) or $address['virtuemart_country_id'] != 0) and in_array($address['virtuemart_country_id'], $countries) || count($countries) == 0) { if ($amount_cond) { return TRUE; } } elseif (empty($address) or $address['virtuemart_country_id'] == 0) { if ($amount_cond) { return TRUE; } } return FALSE; } /** * @param $method */ function convert ($method) { $method->min_amount = (float)$method->min_amount; $method->max_amount = (float)$method->max_amount; } /** * We must reimplement this triggers for joomla 1.7 */ /** * Create the table for this plugin if it does not yet exist. * This functions checks if the called plugin is active one. * When yes it is calling the standard method to create the tables * * @author Valérie Isaksen * */ function plgVmOnStoreInstallPaymentPluginTable ($jplugin_id) { 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. * * @author Valérie isaksen * * @param VirtueMartCart $cart: the actual cart * @return null if the payment was not selected, true if the data is valid, error message if the data is not vlaid * */ public function plgVmOnSelectCheckPayment (VirtueMartCart $cart, &$msg) { if (!$this->selectedThisByMethodId($cart->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } return true; } /* * plgVmonSelectedCalculatePricePayment * 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. * @author Valerie Isaksen * @cart: VirtueMartCart the current cart * @cart_prices: array the new cart prices * @return null if the method was not selected, false if the payment is not valid any more, true otherwise * * */ /** * @param VirtueMartCart $cart * @param array $cart_prices * @param $cart_prices_name * @return bool|null */ public function plgVmOnSelectedCalculatePricePayment (VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) { return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name); } /** * plgVmOnCheckAutomaticSelectedPayment * 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 * * @author Valerie Isaksen * @param VirtueMartCart cart: the cart object * @return null if no plugin was found, 0 if more then one plugin was found, virtuemart_xxx_id if only one plugin is found * */ 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. * * @param integer $order_id The order ID * @return mixed Null for methods that aren't active, text (HTML) otherwise * @author Valerie Isaksen */ 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. * * @param integer $_virtuemart_order_id The order ID * @param integer $method_id method used for this order * @return mixed Null when for payment methods that were not selected, text (HTML) otherwise * @author Valerie Isaksen */ function plgVmonShowOrderPrintPayment ($order_number, $method_id) { return $this->onShowOrderPrint($order_number, $method_id); } /** * Triggered by updateStatusForOneOrder * When status= pre delivery, possible action CancelReservation or ChangeReservation * When status= delivery, possible action ActivateReservation * When status= post delivery, possible action CreditInvoice, Return Amount, CreditPart * * @param array $order order data * @return mixed, True on success, false on failures (the rest of the save-process will be * skipped!), or null when this method is not actived. */ public function plgVmOnUpdateOrderPayment (&$order, $old_order_status) { // get latest info from DB if (!$this->selectedThisByMethodId($order->virtuemart_paymentmethod_id)) { return NULL; // Another method was selected, do nothing } if (!($this->method = $this->getVmPluginMethod($order->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!($payments = $this->getDatasByOrderId($order->virtuemart_order_id))) { vmError(JText::sprintf('VMPAYMENT_KLARNA_ERROR_NO_DATA', $order->virtuemart_order_id), JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); $this->debugLog('No klarna data for this order:' . $order->virtuemart_order_id, 'plgVmOnUpdateOrderPayment', 'error'); $this->debugLog($payments, 'plgVmOnUpdateOrderPayment', 'debug'); return NULL; } //plgVmPaymentKlarnaCheckout::includeKlarnaFiles(); $new_order_status = $order->order_status; $lastPayment = $payments[(count($payments)) - 1]; $klarna_status = $lastPayment->klarna_status; $actions = array('activate', 'cancelReservation', 'changeReservation', 'creditInvoice'); foreach ($actions as $action) { $status = 'status_' . $action; //vmError($action.' '.$this->method->$status.' '.$new_order_status); if ($this->method->$status == $new_order_status and $this->authorizedAction($klarna_status, $new_order_status, $old_order_status, $action, $this->method)) { $this->$action($order, $payments); return true; } } // may be it is another new order status unknown? // TO DO ... how can we disply that when not in push vmError(JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ACTION_NOT_AUTHORIZED', $new_order_status, $lastPayment->klarna_status), JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); $this->debugLog(JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ACTION_NOT_AUTHORIZED', $action, $lastPayment->klarna_status), 'plgVmOnUpdateOrderPayment', 'error'); // true means plugin call was successfull return true; } function authorizedAction ($klarna_status, $new_order_status, $old_order_status, $action) { return true; if ($old_order_status == $this->method->status_checkout_complete) { $authorize = array( 'cancelReservation' => $this->method->status_cancelReservation, 'changeReservation' => $this->method->status_changeReservation, 'activate' => $this->method->status_activate, ); if (in_array($new_order_status, $authorize)) { return TRUE; } } elseif ($old_order_status == $this->method->status_activate) { $authorize = array( 'creditInvoice' => $this->method->status_creditInvoice, 'returnAmount' => $this->method->status_returnAmount, 'creditPart' => $this->method->status_creditPart, ); if (in_array($new_order_status, $authorize)) { return TRUE; } } return FALSE; } /** * The following variables are no longer order specific and should be fixed: * pclass, -1 for all Klarna Checkout orders * pno, null for all Klarna Checkout orders * @param $order * @param $method * @param $payments * @return bool */ function activate ($order, $payments) { $rno = $this->getReservationNumber($payments); if (!$rno) { return; // error already sent } // TO DO ASK KLARNA ABOUT KLARNA MODE //$mode = KlarnaHandler::getKlarnaMode($method, $this->getPurchaseCountry($method)); //$ssl = KlarnaHandler::getKlarnaSSL($mode); // Instantiate klarna object. $this->initKlarnaParams($this->method); $klarna = new Klarna_virtuemart(); $klarna->config($this->merchantid, $this->sharedsecret, $this->country_code_3, NULL, $this->currency_code_3, $this->mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type(), $this->ssl); $modelOrder = VmModel::getModel('orders'); try { $return = $klarna->activate($rno); if ($return[0] == 'ok') { VmInfo(JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ACTIVATE_RESERVATION', $rno)); $vm_invoice_name = ''; $invoice_number = $return[1]; $invoiceURL=$this->getInvoice($invoice_number, $vm_invoice_name); $history = array(); $history['customer_notified'] = 0; $history['order_status'] = $this->method->status_activate; $history['comments'] = JText::sprintf('VMPAYMENT_KLARNACHECKOUT_PAYMENT_STATUS_ACTIVATE', $rno); // $order['details']['BT']->order_number); $modelOrder->updateStatusForOneOrder($order->virtuemart_paymentmethod_id, $history, TRUE); $dbValues['order_number'] = $payments[0]->order_number; $dbValues['payment_name'] = ''; $dbValues['virtuemart_paymentmethod_id'] = $payments[0]->virtuemart_paymentmethod_id; $dbValues['action'] = 'activate'; $dbValues['klarna_status'] = 'activate'; $data["InvoiceNumber"] = $invoice_number; $data["InvoicePdf"] = $invoiceURL; $dbValues['data'] = serialize($data); $this->debugLog($dbValues, 'storePSPluginInternalData activate', 'debug'); $values = $this->storePSPluginInternalData($dbValues, $this->_tablepkey); } else { VmError('activate returned KO', JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); } } catch (Exception $e) { VmError($e->getMessage(), JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); $this->debugLog($e->getMessage(), 'activate', 'error'); return FALSE; } return true; } /** * */ function cancelReservation ($order, $payments) { $rno = $this->getReservationNumber($payments); if (!$rno) { return; // error already sent } $this->initKlarnaParams($this->method); $klarna = new Klarna_virtuemart(); $klarna->config($this->merchantid, $this->sharedsecret, $this->country_code_3, NULL, $this->currency_code_3, $this->mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type(), $this->ssl); $modelOrder = VmModel::getModel('orders'); try { $result = $klarna->cancelReservation($rno); $info = JText::sprintf('VMPAYMENT_KLARNACHECKOUT_RESERVATION_CANCELED', $rno); VmInfo($info); $history = array(); $history['customer_notified'] = 1; //$history['order_status'] = $this->method->checkout_complete; $history['comments'] = $info; // $order['details']['BT']->order_number); $modelOrder->updateStatusForOneOrder($order->virtuemart_paymentmethod_id, $history, TRUE); $dbValues['order_number'] = $payments[0]->order_number; $dbValues['payment_name'] = ''; $dbValues['virtuemart_paymentmethod_id'] = $payments[0]->virtuemart_paymentmethod_id; $dbValues['action'] = 'cancelReservation'; $dbValues['klarna_status'] = 'cancelReservation'; $dbValues['data'] = $info; $this->debugLog($dbValues, 'storePSPluginInternalData cancelReservation', 'debug'); $values = $this->storePSPluginInternalData($dbValues, $this->_tablepkey); } catch (Exception $e) { $error = $e->getMessage(); VmError($e->getMessage(), JText::sprintf('VMPAYMENT_KLARNACHECKOUT_ERROR_OCCURRED', $this->method->payment_name)); $this->debugLog($e->getMessage(), 'cancelReservation', 'error'); return FALSE; } //$dbValues['data'] = $vm_invoice_name; return true; } function changeReservation () { } function creditInvoice () { } function creditPart () { } function getReservationNumber ($payments) { foreach ($payments as $payment) { if ($payment->klarna_status == "checkout_complete") { $klarna_order = unserialize($payment->data); //$klarna_order = ($payment->data); return $klarna_order['reservation']; } } vmError('VMPAYMENT_KLARNACHECKOUT_ERROR_NO_RNO', 'VMPAYMENT_KLARNACHECKOUT_ERROR_NO_RNO'); return null; } /** * @param $orderDetails */ function plgVmOnUserOrder (&$orderDetails) { if (!($this->method = $this->getVmPluginMethod($orderDetails->virtuemart_paymentmethod_id))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement($this->method->payment_element)) { return NULL; } if (!($payments = $this->getDatasByOrderId($orderDetails->virtuemart_order_id))) { return NULL; } $orderDetails->order_number = $this->getReservationNumber($payments); return; } /** * @param $orderDetails * @param $data * @return null */ function plgVmOnUserInvoice ($orderDetails, &$data) { if (!($this->method = $this->getVmPluginMethod($orderDetails['virtuemart_paymentmethod_id']))) { return NULL; // Another method was selected, do nothing } if (!$this->selectedThisElement($this->method->payment_element)) { return NULL; } $data['invoice_number'] = 'reservedByPayment_' . $orderDetails['order_number']; // Never send the invoice via email } /** * Save updated orderline data to the method specific table * * @param array $_formData Form data * @return mixed, True on success, false on failures (the rest of the save-process will be * skipped!), or null when this method is not actived. */ public function plgVmOnUpdateOrderLine ($_formData) { return null; } /** * plgVmOnEditOrderLineBE * This method is fired when editing the order line details in the backend. * It can be used to add line specific package codes * * @param integer $_orderId The order ID * @param integer $_lineId * @return mixed Null for method that aren't active, text (HTML) otherwise public function plgVmOnEditOrderLineBE( $_orderId, $_lineId) { return null; } */ /** * This method is fired when showing the order details in the frontend, for every orderline. * It can be used to display line specific package codes, e.g. with a link to external tracking and * tracing systems * * @param integer $_orderId The order ID * @param integer $_lineId * @return mixed Null for method that aren't active, text (HTML) otherwise public function plgVmOnShowOrderLineFE( $_orderId, $_lineId) { return null; } */ function plgVmDeclarePluginParamsPayment ($name, $id, &$data) { return $this->declarePluginParams('payment', $name, $id, $data); } /** * @param $name * @param $id * @param $table * @return bool */ function plgVmSetOnTablePluginParamsPayment ($name, $id, &$table) { return $this->setOnTablePluginParams($name, $id, $table); } static function getSuccessUrl ($order) { return JURI::root()."index.php?option=com_virtuemart&view=pluginresponse&task=pluginresponsereceived&pm=" . $order['details']['BT']->virtuemart_paymentmethod_id . '&on=' . $order['details']['BT']->order_number . "&Itemid=" . JRequest::getInt('Itemid').'&lang='.JRequest::getCmd('lang',''); } static function getCancelUrl ($order) { return JURI::root()."index.php?option=com_virtuemart&view=pluginresponse&task=pluginUserPaymentCancel&pm=" . $order['details']['BT']->virtuemart_paymentmethod_id . '&on=' . $order['details']['BT']->order_number . '&Itemid=' . JRequest::getInt('Itemid'). '&lang='.JRequest::getCmd('lang',''); } static function getNotificationUrl ($order_number) { return JURI::root()."index.php?option=com_virtuemart&view=pluginresponse&task=pluginnotification&on=" . $order_number. '&lang='.JRequest::getCmd('lang','') ; } /** * @return mixed */ function _getVendorCurrencyId () { if (!class_exists('VirtueMartModelVendor')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'); } $vendor_id = 1; $vendor_currency = VirtueMartModelVendor::getVendorCurrency($vendor_id); return $vendor_currency->virtuemart_currency_id; } /** * */ static function includeKlarnaFiles () { require(JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'klarna' . DS . 'helpers' . DS . 'define.php'); if (!class_exists('KlarnaHandler')) { require(JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnahandler.php'); } if (!class_exists ('klarna_virtuemart')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarna_virtuemart.php'); } require_once(JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'transport' . DS . 'xmlrpc-3.0.0.beta' . DS . 'lib' . DS . 'xmlrpc.inc'); require_once(JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'transport' . DS . 'xmlrpc-3.0.0.beta' . DS . 'lib' . DS . 'xmlrpc_wrappers.inc'); } /** * @param $klarna_invoice_pdf * @param $vm_invoice_name * @return bool */ function getInvoice ($invoice_number, &$vm_invoice_name) { //$klarna_invoice = explode ('/', $klarna_invoice_pdf); if ($this->method->server =='live') { $klarna_invoice_name = "https://online.klarna.com/packslips/" . $invoice_number . '.pdf'; } else { $klarna_invoice_name = "https://online.testdrive.klarna.com/packslips/" . $invoice_number . '.pdf'; } $vm_invoice_name = 'klarna_' . $invoice_number . '.pdf'; return $klarna_invoice_name; } /** * @return int|null|string */ function getInvoicePdfLink ($virtuemart_order_id) { 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'); } if (!($payments = $this->getDatasByOrderId($virtuemart_order_id))) { return ''; } foreach ($payments as $payment) { if ($payment->klarna_status == 'activate') { $data = unserialize($payment->data); $path = VmConfig::get('forSale_path', 0); $path .= 'invoices' . DS; $fileName = $data["InvoicePdf"]; break; } } return $fileName; } } // No closing tag klarnacheckout/klarnacheckout/elements/paymentlogo.php000066600000003410151372777310017442 0ustar00 '; return $logo ; } } }klarnacheckout/klarnacheckout/elements/vmcountry.php000066600000003126151372777310017156 0ustar00setQuery($query); $fields = $db->loadObjectList(); $class = ''; //$class = 'multiple="true" size="10" '; return JHTML::_('select.genericlist', $fields, $control_name . '[' . $name . ']', $class, 'value', 'text', $value, $control_name . $name); } }klarnacheckout/klarnacheckout/elements/.htaccess000066600000000177151372777310016200 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/elements/getklarnacheckout.php000066600000006725151372777310020616 0ustar00getTag (); $langArray = explode ("-", $lang); $lang = strtolower ($langArray[1]); $countriesData = KlarnaHandler::countriesData (); $signLang = "en"; foreach ($countriesData as $countryData) { if ($countryData['country_code'] == $lang) { $signLang = $lang; break; } } /* $logo = ' '; */ $logo = ''; $html = '' . $logo . ''; // https://merchants.klarna.com/signup?locale=en&partner_id=7829355537eae268a17667c199e7c7662d3391f7&utm_campaign=Platform&utm_medium=Partners&utm_source=Virtuemart $html .= '
'; $url = "https://merchants.klarna.com/signup/?locale=" . $signLang . "&partner_id=7829355537eae268a17667c199e7c7662d3391f7&utm_campaign=Platform&utm_medium=Partners&utm_source=Virtuemart"; $js = ' jQuery(document).ready(function( $ ) { $("#klarna_getklarna_show_hide").hide(); jQuery("#klarna_getklarna_link").click( function() { if ( $("#klarna_getklarna_show_hide").is(":visible") ) { $("#klarna_getklarna_show_hide").hide("slow"); $("#klarna_getklarna_link").html("' . addslashes ($logo) . '"); } else { $("#klarna_getklarna_show_hide").show("slow"); $("#klarna_getklarna_link").html("' . addslashes (JText::_ ('VMPAYMENT_KLARNA_GET_KLARNA_HIDE')) . '"); } }); }); '; $doc = JFactory::getDocument (); $doc->addScriptDeclaration ($js); $html .= ''; $html .= '
'; return $html; } }klarnacheckout/klarnacheckout/elements/customjs.php000066600000002347151372777310016763 0ustar00addScript(JURI::root(true).'/plugins/vmpayment/klarnacheckout/klarnacheckout/assets/js/admin.js'); $doc->addStyleSheet(JURI::root(true).'/plugins/vmpayment/klarnacheckout/klarnacheckout/assets/css/klarnacheckout.css'); return ''; } }klarnacheckout/klarnacheckout/elements/getlanguage.php000066600000003106151372777310017371 0ustar00 klarnacheckout/klarnacheckout/.htaccess000066600000000177151372777310014364 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/library/index.html000066600000000000151372777310016210 0ustar00klarnacheckout/klarnacheckout/library/.htaccess000066600000000177151372777310016030 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/library/Checkout.php000066600000004160151372777310016504 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ defined('_JEXEC') or die('Restricted access'); define('KLARNA_CHECKOUT_DIR', dirname(__file__) . '/Checkout'); require_once KLARNA_CHECKOUT_DIR . '/ConnectorInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/ResourceInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/Connector.php'; require_once KLARNA_CHECKOUT_DIR . '/BasicConnector.php'; require_once KLARNA_CHECKOUT_DIR . '/Order.php'; require_once KLARNA_CHECKOUT_DIR . '/Digest.php'; require_once KLARNA_CHECKOUT_DIR . '/Exception.php'; require_once KLARNA_CHECKOUT_DIR . '/ConnectionErrorException.php'; require_once KLARNA_CHECKOUT_DIR . '/ConnectorException.php'; require_once KLARNA_CHECKOUT_DIR . '/UserAgent.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/TransportInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHandleInterface.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Request.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Response.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/Transport.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLTransport.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHeaders.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLHandle.php'; require_once KLARNA_CHECKOUT_DIR . '/HTTP/CURLFactory.php'; klarnacheckout/klarnacheckout/library/Checkout/ConnectorException.php000066600000002575151372777310022325 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connector exception * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_ConnectorException extends Klarna_Checkout_Exception { }klarnacheckout/klarnacheckout/library/Checkout/BasicConnector.php000066600000023242151372777310021402 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Basic implementation of the connector interface * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_BasicConnector implements Klarna_Checkout_ConnectorInterface { /** * Klarna_Checkout_HTTP_TransportInterface Implementation * * @var Klarna_Checkout_HTTP_TransportInterface */ protected $http; /** * Digester class * * @var Klarna_Checkout_Digest */ protected $digester; /** * Shared Secret used to sign requests * * @var string */ private $_secret; /** * Create a new Checkout Connector * * @param Klarna_Checkout_HTTP_TransportInterface $http transport * @param Klarna_Checkout_Digest $digester Digest Generator * @param string $secret shared secret */ public function __construct( Klarna_Checkout_HTTP_TransportInterface $http, Klarna_Checkout_Digest $digester, $secret ) { $this->http = $http; $this->digester = $digester; $this->_secret = $secret; } /** * Create the user agent identifier to use * * @return Klarna_Checkout_UserAgent */ protected function userAgent() { return new Klarna_Checkout_UserAgent(); } /** * Applying the method on the specific resource * * @param string $method Http methods * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return mixed */ public function apply( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null ) { switch ($method) { case 'GET': case 'POST': return $this->handle($method, $resource, $options, array()); default: throw new InvalidArgumentException( "{$method} is not a valid HTTP method" ); } } /** * Gets the underlying transport object * * @return Klarna_Checkout_HTTP_TransportInterface Transport object */ public function getTransport() { return $this->http; } /** * Set content (headers, payload) on a request * * @param Klarna_Checkout_ResourceInterface $resource Klarna Checkout Resource * @param string $method HTTP Method * @param string $payload Payload to send with the * request * @param string $url URL for request * * @return Klarna_Checkout_HTTP_Request */ protected function createRequest( Klarna_Checkout_ResourceInterface $resource, $method, $payload, $url ) { // Generate the digest string $digest = $this->digester->create($payload . $this->_secret); $request = $this->http->createRequest($url); $request->setMethod($method); // Set HTTP Headers $request->setHeader('User-Agent', (string)$this->userAgent()); $request->setHeader('Authorization', "Klarna {$digest}"); $request->setHeader('Accept', $resource->getContentType()); if (strlen($payload) > 0) { $request->setHeader('Content-Type', $resource->getContentType()); $request->setData($payload); } return $request; } /** * Get the url to use * * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return string Url to use for HTTP requests */ protected function getUrl( Klarna_Checkout_ResourceInterface $resource, array $options ) { if (array_key_exists('url', $options)) { return $options['url']; } return $resource->getLocation(); } /** * Get the data to use * * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return array data to use for HTTP requests */ protected function getData( Klarna_Checkout_ResourceInterface $resource, array $options ) { if (array_key_exists('data', $options)) { return $options['data']; } return $resource->marshal(); } /** * Throw an exception if the server responds with an error code. * * @param Klarna_Checkout_HTTP_Response $result HTTP Response object * * @throws Klarna_Checkout_HTTP_Status_Exception * @return void */ protected function verifyResponse(Klarna_Checkout_HTTP_Response $result) { // Error Status Code recieved. Throw an exception. if ($result->getStatus() >= 400 && $result->getStatus() <= 599) { throw new Klarna_Checkout_ConnectorException( $result->getData(), $result->getStatus() ); } } /** * Act upon the status of a response * * @param Klarna_Checkout_HTTP_Response $result response from server * @param Klarna_Checkout_ResourceInterface $resource associated resource * @param array $visited list of visited locations * * @return Klarna_Checkout_HTTP_Response */ protected function handleResponse( Klarna_Checkout_HTTP_Response $result, Klarna_Checkout_ResourceInterface $resource, array $visited = array() ) { // Check if we got an Error status code back $this->verifyResponse($result); $url = $result->getHeader('Location'); switch ($result->getStatus()) { case 301: // Update location and fallthrough $resource->setLocation($url); case 302: // Don't fallthrough for other than GET if ($result->getRequest()->getMethod() !== 'GET') { break; } case 303: // Detect eternal loops if (in_array($url, $visited)) { throw new Klarna_Checkout_ConnectorException( 'Infinite redirect loop detected.', -1 ); } $visited[] = $url; // Follow redirect return $this->handle( 'GET', $resource, array('url' => $url), $visited ); case 201: // Update Location $resource->setLocation($url); break; case 200: // Update Data on resource $json = json_decode($result->getData(), true); if ($json === null) { throw new Klarna_Checkout_ConnectorException( 'Bad format on response content.', -2 ); } $resource->parse($json); } return $result; } /** * Perform a HTTP Call on the supplied resource using the wanted method. * * @param string $method HTTP Method * @param Klarna_Checkout_ResourceInterface $resource Klarna Order * @param array $options Options * @param array $visited list of visited locations * * @throws Klarna_Checkout_Exception if 4xx or 5xx response code. * @return Result object containing status code and payload */ protected function handle( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null, array $visited = array() ) { if ($options === null) { $options = array(); } // Define the target URL $url = $this->getUrl($resource, $options); // Set a payload if it is a POST call. $payload = ''; if ($method === 'POST') { $payload = json_encode($this->getData($resource, $options)); } // Create a HTTP Request object $request = $this->createRequest($resource, $method, $payload, $url); // $this->_setContent($request, $payload, $method); // Execute the HTTP Request $result = $this->http->send($request); // Handle statuses appropriately. return $this->handleResponse($result, $resource, $visited); } } klarnacheckout/klarnacheckout/library/Checkout/Exception.php000066600000002535151372777310020446 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Basic exception class * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Exception extends Exception { }klarnacheckout/klarnacheckout/library/Checkout/ConnectionErrorException.php000066600000002637151372777310023503 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connection exception * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_ConnectionErrorException extends Klarna_Checkout_Exception { } klarnacheckout/klarnacheckout/library/Checkout/ConnectorInterface.php000066600000003720151372777310022260 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for the resource object * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_ConnectorInterface { /** * Applying the method on the specific resource * * @param string $method Http methods * @param Klarna_Checkout_ResourceInterface $resource resource * @param array $options Options * * @return void */ public function apply( $method, Klarna_Checkout_ResourceInterface $resource, array $options = null ); /** * Gets the underlying transport object * * @return Klarna_Checkout_HTTP_TransportInterface Transport object */ public function getTransport(); } klarnacheckout/klarnacheckout/library/Checkout/ResourceInterface.php000066600000004070151372777310022114 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for the resource object * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_ResourceInterface { /** * Get the URL of the resource * * @return string */ public function getLocation(); /** * Set the URL of the resource * * @param string $location URL of the resource * * @return void */ public function setLocation($location); /** * Return content type of the resource * * @return string Content type */ public function getContentType(); /** * Update resource with the new data * * @param array $data data * * @return void */ public function parse(array $data); /** * Basic representation of the object * * @return array data */ public function marshal(); } klarnacheckout/klarnacheckout/library/Checkout/Order.php000066600000013015151372777310017556 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Implementation of the order resource * * @category Payment * @package Klarna_Checkout * @author Majid G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Order implements Klarna_Checkout_ResourceInterface, ArrayAccess { /** * Base URI that is used to create order resources * * @var string */ public static $baseUri = null; /** * Content Type to use * * @var string */ public static $contentType = null; /** * URI of remote resource * * @var string */ private $_location; /** * Order data * * @var array */ private $_data = array(); /** * Connector * * @var Klarna_Checkout_ConnectorInterface */ protected $connector; /** * Create a new Order object * * @param Klarna_Checkout_ConnectorInterface $connector connector to use * @param string $uri uri of resource * * @return void */ public function __construct( Klarna_Checkout_ConnectorInterface $connector, $uri = null ) { $this->connector = $connector; if ($uri !== null) { $this->setLocation($uri); } } /** * Get the URL of the resource * * @return string */ public function getLocation() { return $this->_location; } /** * Set the URL of the resource * * @param string $location URL of the resource * * @return void */ public function setLocation($location) { $this->_location = strval($location); } /** * Return content type of the resource * * @return string Content type */ public function getContentType() { return self::$contentType; } /** * Replace resource data * * @param array $data data * * @return void */ public function parse(array $data) { $this->_data = $data; } /** * Basic representation of the object * * @return array Data */ public function marshal() { return $this->_data; } /** * Create a new order * * @param array $data data to initialise order resource with * * @return void */ public function create(array $data) { $options = array( 'url' => self::$baseUri, 'data' => $data ); $this->connector->apply('POST', $this, $options); } /** * Fetch order data * * @return void */ public function fetch() { $options = array( 'url' => $this->_location ); $this->connector->apply('GET', $this, $options); } /** * Update order data * * @param array $data data to update order resource with * * @return void */ public function update( array $data ) { $options = array( 'url' => $this->_location, 'data' => $data ); $this->connector->apply('POST', $this, $options); } /** * Get value of a key * * @param string $key Key * * @return mixed data */ public function offsetGet($key) { if (!is_string($key)) { throw new InvalidArgumentException("Key must be string"); } return $this->_data[$key]; } /** * Set value of a key * * @param string $key Key * @param mixed $value Value of the key * * @return void */ public function offsetSet($key, $value) { if (!is_string($key)) { throw new InvalidArgumentException("Key must be string"); } $value = print_r($value, true); throw new RuntimeException( "Use update function to change values. trying to set $key to $value" ); } /** * Check if a key exists in the resource * * @param string $key key * * @return boolean */ public function offsetExists($key) { return array_key_exists($key, $this->_data); } /** * Unset the value of a key * * @param string $key key * * @return void */ public function offsetUnset($key) { throw new RuntimeException( "unset of fields not supported. trying to unset $key" ); } } klarnacheckout/klarnacheckout/library/Checkout/index.html000066600000000000151372777310017755 0ustar00klarnacheckout/klarnacheckout/library/Checkout/UserAgent.php000066600000005541151372777310020405 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * UserAgent string builder * * @category Payment * @package Klarna_Checkout * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_UserAgent { /** * Components of the user-agent * * @var array */ private $_fields; /** * Initialise user-agent with default fields */ public function __construct() { $this->_fields = array( 'Library' => array( 'name' => 'Klarna.ApiWrapper', 'version' => '1.1.0', ), 'OS' => array( 'name' => php_uname('s'), 'version' => php_uname('r') ), 'Language' => array( 'name' => 'PHP', 'version' => phpversion() ) ); } /** * Add a new field to the user agent * * @param string $field Name of field * @param array $data data array with name, version and possibly options * * @return void */ public function addField($field, array $data) { if (array_key_exists($field, $this->_fields)) { throw new Klarna_Checkout_Exception( "Unable to redefine field {$field}" ); } $this->_fields[$field] = $data; } /** * Serialise fields to a user agent string * * @return string */ public function __toString() { $parts = array(); foreach ($this->_fields as $key => $value) { $parts[] = "$key/{$value['name']}_{$value['version']}"; if (array_key_exists('options', $value)) { $parts[] = '(' . implode(' ; ', $value['options']) . ')'; } } return implode(' ', $parts); } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/Transport.php000066600000003147151372777310021263 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Factory of HTTP Transport * * @category Payment * @package Payment_Klarna * @subpackage Unit_Tests * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Transport { /** * Create a new transport instance * * @return Klarna_Checkout_HTTP_TransportInterface */ public static function create() { return new Klarna_Checkout_HTTP_CURLTransport( new Klarna_Checkout_HTTP_CURLFactory ); } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/TransportInterface.php000066600000005153151372777310023103 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Interface for a Klarna HTTP Transport object * * @category Payment * @package Payment_Klarna * @subpackage Interfaces * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_HTTP_TransportInterface { /** * Specifies the number of seconds before the connection times out. * * @param int $timeout number of seconds * * @throws InvalidArgumentException If the specified argument * is not of type integer. * @return void */ public function setTimeout($timeout); /** * Gets the number of seconds before the connection times out. * * @return int timeout in number of seconds */ public function getTimeout(); /** * Performs a HTTP request. * * @param Klarna_Checkout_HTTP_Request $request the HTTP request to send. * * @throws Klarna_Checkout_ConnectionErrorException Thrown for unspecified * network or hardware issues. * @return Klarna_Checkout_HTTP_Response */ public function send(Klarna_Checkout_HTTP_Request $request); /** * Creates a HTTP request object. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return Klarna_Checkout_HTTP_Request */ public function createRequest($url); } klarnacheckout/klarnacheckout/library/Checkout/HTTP/index.html000066600000000000151372777310020534 0ustar00klarnacheckout/klarnacheckout/library/Checkout/HTTP/CURLHeaders.php000066600000004761151372777310021333 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * A simple class handling the header callback for cURL. * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLHeaders { /** * Response headers, cleared for each request. * * @var array */ protected $headers; /** * Initializes a new instance of the HTTP cURL class. */ public function __construct() { $this->headers = array(); } /** * Callback method to handle custom headers. * * @param resource $curl the cURL resource. * @param string $header the header data. * * @return int the number of bytes handled. */ public function processHeader($curl, $header) { $curl = null; //TODO replace with regexp, e.g. /^([^:]+):([^:]*)$/ ? $pos = strpos($header, ':'); // Didn't find a colon. if ($pos === false) { // Not real header, abort. return strlen($header); } $key = substr($header, 0, $pos); $value = trim(substr($header, $pos+1)); $this->headers[$key] = trim($value); return strlen($header); } /** * Gets the accumulated headers. * * @return array */ public function getHeaders() { return $this->headers; } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/CURLTransport.php000066600000012411151372777310021743 0ustar00 * @copyright 2012 Klarna AB AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP transport implementation for cURL * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLTransport implements Klarna_Checkout_HTTP_TransportInterface { const DEFAULT_TIMEOUT = 10; /** * @var Klarna_Checkout_HTTP_CURLFactory */ protected $curl; /** * Number of seconds before the connection times out. * * @var int */ protected $timeout; /** * Initializes a new instance of the HTTP cURL class. * * @param Klarna_Checkout_HTTP_CURLFactory $curl factory to for curl handles */ public function __construct(Klarna_Checkout_HTTP_CURLFactory $curl) { $this->curl = $curl; $this->timeout = self::DEFAULT_TIMEOUT; } /** * Sets the number of seconds until a connection times out. * * @param int $timeout number of seconds * * @return void */ public function setTimeout($timeout) { $this->timeout = intval($timeout); } /** * Gets the number of seconds before the connection times out. * * @return int timeout in number of seconds */ public function getTimeout() { return $this->timeout; } /** * Performs a HTTP request. * * @param Klarna_Checkout_HTTP_Request $request the HTTP request to send. * * @throws RuntimeException Thrown if a cURL handle cannot * be initialized. * @throws Klarna_Checkout_ConnectionErrorException Thrown for unspecified * network or hardware issues. * @return Klarna_Checkout_HTTP_Response */ public function send(Klarna_Checkout_HTTP_Request $request) { $curl = $this->curl->handle(); if ($curl === false) { throw new RuntimeException( 'Failed to initialize a HTTP handle.' ); } $url = $request->getURL(); $curl->setOption(CURLOPT_URL, $url); $method = $request->getMethod(); if ($method === 'POST') { $curl->setOption(CURLOPT_POST, true); $curl->setOption(CURLOPT_POSTFIELDS, $request->getData()); } // Convert headers to cURL format. $requestHeaders = array(); foreach ($request->getHeaders() as $key => $value) { $requestHeaders[] = $key . ': ' . $value; } $curl->setOption(CURLOPT_HTTPHEADER, $requestHeaders); $curl->setOption(CURLOPT_RETURNTRANSFER, true); $curl->setOption(CURLOPT_CONNECTTIMEOUT, $this->timeout); $curlHeaders = new Klarna_Checkout_HTTP_CURLHeaders(); $curl->setOption( CURLOPT_HEADERFUNCTION, array(&$curlHeaders, 'processHeader') ); // TODO remove me when real cert is in place $curl->setOption(CURLOPT_SSL_VERIFYPEER, false); $payload = $curl->execute(); $info = $curl->getInfo(); $curl->close(); /* * A failure occured if: * payload is false (e.g. HTTP timeout?). * info is false, then it has no HTTP status code. */ if ($payload === false || $info === false) { throw new Klarna_Checkout_ConnectionErrorException( "Connection to '{$url}' failed." ); } $headers = $curlHeaders->getHeaders(); // Convert Content-Type into a normal header $headers['Content-Type'] = $info['content_type']; $response = new Klarna_Checkout_HTTP_Response( $request, $headers, intval($info['http_code']), strval($payload) ); return $response; } /** * Creates a HTTP request object. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return Klarna_Checkout_HTTP_Request */ public function createRequest($url) { return new Klarna_Checkout_HTTP_Request($url); } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/CURLHandleInterface.php000066600000003661151372777310022772 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Defines a cURL handle interface * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ interface Klarna_Checkout_HTTP_CURLHandleInterface { /** * Set an option for the cURL transfer * * @param int $name option the set * @param mixed $value the value to be set on option * * @return void */ public function setOption($name, $value); /** * Perform the cURL session * * @return mixed response */ public function execute(); /** * Get information regarding this transfer * * @return array */ public function getInfo(); /** * Close the cURL session * * @return void */ public function close(); } klarnacheckout/klarnacheckout/library/Checkout/HTTP/Request.php000066600000010605151372777310020714 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP Request class * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Request { /** * @var string */ protected $url; /** * @var string */ protected $method; /** * @var array */ protected $headers; /** * @var string */ protected $data; /** * Initializes a new instance of the HTTP request class. * * @param string $url the request URL. * * @throws InvalidArgumentException If the specified argument * is not of type string. */ public function __construct($url) { $this->url = $url; $this->method = 'GET'; $this->headers = array(); $this->data = ''; } /** * Gets the request URL. * * @return string the request URL. */ public function getURL() { return $this->url; } /** * Specifies the HTTP method used for the request. * * @param string $method a HTTP method. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return void */ public function setMethod($method) { $this->method = strtoupper($method); } /** * Gets the HTTP method used for the request. * * @return string a HTTP method */ public function getMethod() { return $this->method; } /** * Specifies a header for the request. * * @param string $name the header name * @param mixed $value the header value * * @throws InvalidArgumentException If the argument name is not of type * string or an empty string. * @return void */ public function setHeader($name, $value) { $this->headers[$name] = strval($value); } /** * Gets a specific header for the request. * * @param string $name the header name * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return string|null the header value or null if it doesn't exist */ public function getHeader($name) { if (!array_key_exists($name, $this->headers)) { return null; } return $this->headers[$name]; } /** * Gets the headers specified for the request. * * @return array */ public function getHeaders() { return $this->headers; } /** * Sets the data (payload) for the request. * * \code * $request->setMethod('POST'); * $request->setData('some data'); * \endcode * * @param string $data the request payload * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return void */ public function setData($data) { $this->data = $data; } /** * Gets the data (payload) for the request. * * @return string the request payload */ public function getData() { return $this->data; } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/Response.php000066600000007040151372777310021061 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Klarna HTTP Response class * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_Response { /** * @var int */ protected $status; /** * @var Klarna_Checkout_HTTP_Request */ protected $request; /** * @var array */ protected $headers; /** * @var string */ protected $data; /** * Initializes a new instance of the HTTP response class. * * @param Klarna_Checkout_HTTP_Request $request the origin request. * @param array $headers the response HTTP headers. * @param int $status the HTTP status code. * @param string $data the response payload. */ public function __construct( Klarna_Checkout_HTTP_Request $request, array $headers, $status, $data ) { $this->request = $request; $this->headers = array(); foreach ($headers as $key => $value) { $this->headers[strtolower($key)] = $value; } $this->status = $status; $this->data = $data; } /** * Gets the HTTP status code. * * @return int HTTP status code. */ public function getStatus() { return $this->status; } /** * Gets the HTTP request this response originated from. * * @return Klarna_Checkout_HTTP_Request */ public function getRequest() { return $this->request; } /** * Gets specified HTTP header. * * @param string $name the header name. * * @throws InvalidArgumentException If the specified argument * is not of type string. * @return string|null Null if header doesn't exist, else header value. */ public function getHeader($name) { $name = strtolower($name); if (!array_key_exists($name, $this->headers)) { return null; } return $this->headers[$name]; } /** * Gets the headers specified for the response. * * @return array */ public function getHeaders() { return $this->headers; } /** * Gets the data (payload) for the response. * * @return string the response payload. */ public function getData() { return $this->data; } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/CURLHandle.php000066600000005055151372777310021150 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * A wrapper around the cURL functions * * @category Payment * @package Payment_Klarna * @subpackage HTTP * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLHandle implements Klarna_Checkout_HTTP_CURLHandleInterface { /** * cURL handle * @var resource */ private $_handle = null; /** * Create a new cURL handle */ public function __construct() { if (!extension_loaded('curl')) { throw new RuntimeException( 'cURL extension is requred.' ); } $this->_handle = curl_init(); } /** * Set an option for the cURL transfer * * @param int $name option the set * @param mixed $value the value to be set on option * * @return void */ public function setOption($name, $value) { curl_setopt($this->_handle, $name, $value); } /** * Perform the cURL session * * @return mixed response */ public function execute() { return curl_exec($this->_handle); } /** * Get information regarding this transfer * * @return array */ public function getInfo() { return curl_getinfo($this->_handle); } /** * Close the cURL session * * @return void */ public function close() { curl_close($this->_handle); } } klarnacheckout/klarnacheckout/library/Checkout/HTTP/.htaccess000066600000000177151372777310020354 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/library/Checkout/HTTP/CURLFactory.php000066600000003041151372777310021355 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Factory of cURL handles * * @category Payment * @package Payment_Klarna * @subpackage Unit_Tests * @author Klarna * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_HTTP_CURLFactory { /** * Create a new cURL handle * * @return Klarna_Checkout_HTTP_CURLHandle */ public function handle() { return new Klarna_Checkout_HTTP_CURLHandle(); } } klarnacheckout/klarnacheckout/library/Checkout/Digest.php000066600000003224151372777310017723 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Class to handle the digesting of hash string * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Digest { /** * create a digest from a supplied string * * @param string $digestString string to hash * * @return string Base64 and SHA256 hashed string */ public function create($digestString) { return base64_encode(hash('sha256', $digestString, true)); } } klarnacheckout/klarnacheckout/library/Checkout/Connector.php000066600000003441151372777310020437 0ustar00 * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ /** * Connector factory * * @category Payment * @package Klarna_Checkout * @author Rickard D. * @author Christer G. * @author David K. * @copyright 2012 Klarna AB * @license http://www.apache.org/licenses/LICENSE-2.0 Apache license v2.0 * @link http://integration.klarna.com/ */ class Klarna_Checkout_Connector { /** * Create a new Checkout Connector * * @param string $secret string used to sign requests * * @return Klarna_Checkout_ConnectorInterface */ public static function create($secret) { return new Klarna_Checkout_BasicConnector( Klarna_Checkout_HTTP_Transport::create(), new Klarna_Checkout_Digest, $secret ); } } klarnacheckout/klarnacheckout/library/Checkout/.htaccess000066600000000177151372777310017575 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/tmpl/response_received.php000066600000001620151372777310017751 0ustar00
klarnacheckout/klarnacheckout/tmpl/cart_advertisement.php000066600000002654151372777310020140 0ustar00addStyleDeclaration($css); $js = ' jQuery(document).ready(function( $ ) { $("#checkoutForm").hide(); }); '; if ($viewData ['hide_BTST']) { $js .= ' jQuery(document).ready(function( $ ) { $(".billto-shipto").hide(); $("#com-form-login").hide(); }); '; } $document = JFactory::getDocument(); $document->addScriptDeclaration ( $js); ?>

klarnacheckout/klarnacheckout/tmpl/display_payment.php000066600000003445151372777310017456 0ustar00 > klarnacheckout/klarnacheckout/tmpl/render_pluginname.php000066600000002270151372777310017745 0ustar00 klarnacheckout/klarnacheckout/tmpl/.htaccess000066600000000177151372777310015340 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/tmpl/order_fe.php000066600000002167151372777310016041 0ustar00
sofort_response_transaction; ?>
klarnacheckout/klarnacheckout/tmpl/index.html000066600000000057151372777310015534 0ustar00 klarnacheckout/klarnacheckout/tmpl/show_order.php000066600000001645151372777310016427 0ustar00
klarnacheckout/klarnacheckout/assets/css/index.html000066600000000000151372777310016636 0ustar00klarnacheckout/klarnacheckout/assets/css/.htaccess000066600000000177151372777310016456 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/assets/css/klarnacheckout.css000066600000000557151372777310020372 0ustar00#checkoutForm { display: none; } .show_payment_logo { margin: 10px 0 5px 0; font-weight: bold; padding: 5px; float:none; clear:both; background-color: #FFFFFF !important; background:url(https://cdn.klarna.com/public/images/SE/logos/v1/basic/SE_basic_logo_std_blue-black.png?width=100) no-repeat; height: 40px; padding-left:100px !important; }klarnacheckout/klarnacheckout/assets/index.html000066600000000000151372777310016046 0ustar00klarnacheckout/klarnacheckout/assets/js/admin.js000066600000001442151372777310016126 0ustar00/** * @package VmPayment PayPal * @author Jeremy Magne * @copyright Copyright (C) 2010 Daycounts.com. All Rights Reserved. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ jQuery().ready(function($) { /************/ /* Handlers */ /************/ handleLogo = function() { var payment_logos = $("input[name='params[payment_logos]']:checked").val(); $('.show_payment_logo').parents('tr').hide(); if (payment_logos=='1') { $('.show_payment_logo').parents('tr').show(); } } /**********/ /* Events */ /**********/ $("input[name='params[payment_logos]']").change(function() { handleLogo(); }); /*****************/ /* Initial calls */ /*****************/ handleLogo(); }); klarnacheckout/klarnacheckout/assets/js/.htaccess000066600000000177151372777310016302 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/assets/js/index.html000066600000000000151372777310016462 0ustar00klarnacheckout/klarnacheckout/assets/.htaccess000066600000000177151372777310015666 0ustar00 Order allow,deny Deny from all klarnacheckout/klarnacheckout/index.html000066600000000037151372777310014556 0ustar00 klarnacheckout/.htaccess000066600000000177151372777310011366 0ustar00 Order allow,deny Deny from all klarnacheckout/index.html000066600000000000151372777310011546 0ustar00.htaccess000066600000000177151372777310006370 0ustar00 Order allow,deny Deny from all moneybookers_idl/index.html000066600000000037151372777310012126 0ustar00 moneybookers_idl/moneybookers_idl.php000066600000003164151372777310014212 0ustar00_loggable = true; $this->_debug = false; $this->_tablepkey = 'id'; //virtuemart_moneybookers_id'; $this->_tableId = 'id'; //'virtuemart_moneybookers_id'; } function plgVmConfirmedOrder($cart, $order, $payment_method = '') { parent::plgVmConfirmedOrder($cart, $order, "IDL"); } } // No closing tagmoneybookers_idl/moneybookers_idl.xml000066600000007224151372777310014224 0ustar00 Moneybookers iDeal April 2012 Skrill Holdings Limited http://www.skrill.com Copyright (C) 2012 Skrill. http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL 2.0.6 Moneybookers is a popular payment provider authorised by the Financial Services Authority of the United Kingdom (FSA). ]]> moneybookers_idl.php en-GB.plg_vmpayment_moneybookers_idl.ini en-GB.plg_vmpayment_moneybookers_idl.ini moneybookers_idl/.htaccess000066600000000177151372777310011734 0ustar00 Order allow,deny Deny from all klarna/klarna/helpers/define.php000066600000003775151372777310012726 0ustar00set_language($HTTP_GET_VARS['language']); } else { $lng->get_browser_language(); } $language = $lng->language['directory']; $languages_id = $lng->language['id']; $product_info_query = tep_db_query("select p.products_id, pd.products_name, pd.products_description, p.products_model, p.products_quantity, p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_date_available, p.manufacturers_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . (int)$mProductId . "' and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'"); $aProduct_info = tep_db_fetch_array($product_info_query); $sArtNo = (MODULE_PAYMENT_KLARNA_ARTNO == 'id' || MODULE_PAYMENT_KLARNA_ARTNO == '' ? $aProduct_info['id'] : $aProduct_info['name']); $iTax = tep_get_tax_rate($aProduct_info['products_tax_class_id']); if(DISPLAY_PRICE_WITH_TAX == 'true') { $iPrice_with_tax = $currencies->get_value($currency) * $aProduct_info['products_price']; } else { $iPrice_with_tax = $currencies->get_value($currency) * $aProduct_info['products_price'] * (($iTax/100)+1); } // Add goods $this->oKlarna->addArticle( 1, //Quantity $sArtNo, //Article number $aProduct_info['products_name'], //Article name/title $iPrice_with_tax, // Price $iTax, //25% VAT 0, // Discount KlarnaFlags::INC_VAT // Flag incl. excl vat ); $this->iSum += $iPrice_with_tax; } /** * When a purchase is made, the script returns an redirect-URL or a message. When the URL is returned, the user is re-directed to this page. * This could be an URL to a downloadable file (WARNING! SHOULD ALWAYS BE A DYNAMIC URL!), or a link to a "Thank you"/confirmation page (Comon for donation purposes) * * @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality * @return mixed Either NULL or FALSE if no URL is available, or STRING with full URL when URL is available. */ protected function fetchRedirectUrl ($mProductId) { return "http://www.klarna.com"; } /** * When a purchase is made (approved as well) it might needs to be added to the merchants order system. In this function you can define how the order of a product should be handled. * * @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality * @param integer $iKlarnaReference The reference returned by Klarna * @param string $sTelNo The telephone number used to make a purchase * @return void */ protected function processOrder ($mProductId, $iKlarnaReference, $iTelNo) { // Here you should implement the functionality of how the product is managed. } } klarna/klarna/helpers/klarnaapi.php000066600000066627151372777310013443 0ustar00sPath = $sPath; if ($a_sLangISO == NULL) { $aLangArray = array( "swe" => "sv", "deu" => "de", "dnk" => "da", "nld" => "nl", "nor" => "nb", "fin" => "fi", "en" => "en"); $a_sLangISO = @$aLangArray[strtolower ($a_sCountry)]; } // Set the klarna object $this->oKlarna = &$a_oKlarna; // Validate the submitted values $this->setCountry ($a_sCountry); $this->setLanguage ($a_sLangISO); $this->validateType ($a_sType); /* // Set the default input names $this->aInputParameters['street'] = "street"; $this->aInputParameters['homenumber'] = "homenumber"; $this->aInputParameters['paymentPlan'] = "paymentPlan"; $this->aInputParameters['gender'] = "gender"; $this->aInputParameters['male'] = "male"; $this->aInputParameters['female'] = "female"; $this->aInputParameters['birth_day'] = "birth_day"; $this->aInputParameters['birth_month'] = "birth_month"; $this->aInputParameters['birth_year'] = "birth_year"; $this->aInputParameters['bd_jan'] = "1"; $this->aInputParameters['bd_feb'] = "2"; $this->aInputParameters['bd_mar'] = "3"; $this->aInputParameters['bd_apr'] = "4"; $this->aInputParameters['bd_may'] = "5"; $this->aInputParameters['bd_jun'] = "6"; $this->aInputParameters['bd_jul'] = "7"; $this->aInputParameters['bd_aug'] = "8"; $this->aInputParameters['bd_sep'] = "9"; $this->aInputParameters['bd_oct'] = "10"; $this->aInputParameters['bd_nov'] = "11"; $this->aInputParameters['bd_dec'] = "12"; $this->aInputParameters['socialNumber'] = "socialNumber"; $this->aInputParameters['phoneNumber'] = "phoneNumber"; $this->aInputParameters['year_salary'] = "year_salary"; $this->aInputParameters['house_extension'] = "house_extension"; $this->aInputParameters['shipmentAddressInput'] = "shipment_address"; $this->aInputParameters['emailAddress'] = "emailAddress"; $this->aInputParameters['invoiceType'] = "invoiceType"; $this->aInputParameters['reference'] = "reference"; $this->aInputParameters['companyName'] = "companyName"; $this->aInputParameters['firstName'] = "firstName"; $this->aInputParameters['lastName'] = "lastName"; $this->aInputParameters['invoice_type'] = "invoice_type"; $this->aInputParameters['consent'] = "consent"; $this->aInputParameters['city'] = "city"; $this->aInputParameters['zipcode'] = "zipcode"; // Set the default setup values $this->aSetupSettings['langISO'] = $this->sLangISO; $this->aSetupSettings['countryCode'] = $this->sCountryCode; $this->aSetupSettings['sum'] = $a_iSum; $this->aSetupSettings['flag'] = $a_iFlag; $this->aSetupSettings['payment_id'] = "payment"; $this->aSetupSettings['invoice_name'] = 'klarna_invoice'; $this->aSetupSettings['part_name'] = 'klarna_partPayment'; $this->aSetupSettings['spec_name'] = 'klarna_SpecCamp'; */ // $this->aSetupSettings['web_root'] = "/"; //$this->setPaths(); //$this->country=$this->getCountry(); //?????? // Fetch PClasses in case type is invoice if (($this->sType == 'part' || $this->sType == 'spec') && $this->oKlarna != NULL) { $this->fetchPClasses ($a_iSum, $a_iFlag, $aTypes); } } // public function setPaths() { // $this->aSetupSettings['path_css'] = $this->aSetupSettings['web_root'].VMKLARNAPLUGINWEBROOT. '/klarna/assets/css/'; // $this->aSetupSettings['path_js'] = $this->aSetupSettings['web_root'] .VMKLARNAPLUGINWEBROOT. '/klarna/assets/js/'; // $this->aSetupSettings['path_img'] = $this->aSetupSettings['web_root'] .VMKLARNAPLUGINWEBROOT. '/klarna/assets/images/'; // } /** * Add/Overwrite extra setup values. * * @param string $sName The name of the value * @param string $sValue The value * @return void * @deprecated */ public function addSetupValue ($sName, $sValue) { $this->aSetupSettings[$sName] = $sValue; } /** * Add multiple setup values at once * * @param array $aSetupValues The setup values as array. Key is name, value is value. * @return void * * @deprecated */ public function addMultipleSetupValues ($aSetupValues) { foreach ($aSetupValues as $sName => $sValue) { $this->aSetupSettings[$sName] = $sValue; } } public function getSetupValues () { return $this->aSetupSettings; } /** * Add/Overwrite input values. * * @param string $sName The name of the value * @param string $sValue The value * @return void * @deprecated */ public function addInputValue ($sName, $sValue) { $this->aInputValue[$sName] = $sValue; } /** * Add multiple input values at once * * @param array $aSetupValues The setup values as array. Key is name, value is value. * @return void */ public function addMultipleInputValues ($aInputValues) { foreach ($aInputValues as $sName => $sValue) { $this->aInputValue[$sName] = $sValue; } } /* * * @deprecated */ public function getInputValues () { return $this->aInputValues; } /* * @deprecated * */ public function setInvoiceFee ($fee) { if ($this->sType != 'invoice') { throw new KlarnaApiException("Invoice fee only supported when payment type is invoice"); } $this->aSetupSettings['fee'] = round (floatval ($fee), 1); } /** * Retrieve the finished HTML * * @param array $a_aParams The input field names. Only submitted for those that should be different from default values * @param string $a_sHTMLFile (Optional) The file to import. If not submitted, which HTML file will be decides by the class * @return string * @deprecated */ public function retrieveHTML ($a_aParams = NULL, $a_aValues = NULL, $a_sHTMLFile = NULL, $aTemplateData = NULL) { if ($a_aValues != NULL) { $this->aInputValues = array_merge ( $this->aInputValues, $a_aValues); } if ($a_aParams != NULL) { $this->aInputParameters = array_merge ( $this->aInputParameters, $a_aParams); } // print_r($this->aInputValues); // Backwards compability // using input values for red baloon is DEPRECATED if (array_key_exists ('red_baloon_content', $this->aInputValues)) { $this->aSetupSettings['red_baloon_content'] = $this->aInputValues['red_baloon_content']; } if (array_key_exists ('red_baloon_paymentBox', $this->aInputValues)) { $this->aSetupSettings['red_baloon_paymentBox'] = $this->aInputValues['red_baloon_paymentBox']; } if (is_array ($this->aPClasses)) { foreach ($this->aPClasses as $pclass) { if ($pclass['default'] === TRUE) { $this->aInputValues['paymentPlan'] = $pclass['pclass']->getId (); break; } } } $sTemplate = $this->loadTemplate ($a_sHTMLFile, $aTemplateData); Klarna::printDebug (__METHOD__ . ' setup settings', $this->aSetupSettings); Klarna::printDebug (__METHOD__ . ' input values', $this->aInputValues); return $this->translateInputFields ($sTemplate); } /** * @param null $a_sHTMLFile * @param null $aTemplateData * @return string * @deprecated */ public function loadTemplate ($a_sHTMLFile = NULL, $aTemplateData = NULL) { $sFilename = ''; /** * @todo Check for file and trow error if missing */ if ($a_sHTMLFile != NULL) { $sFilename = $a_sHTMLFile; } else { if ($this->sType != "spec") { $sFilename = ($this->sPath != NULL ? $this->sPath : "") . "/klarna/tmpl/" . $this->sType . "_" . strtolower ($this->sCountryCode) . ".html"; } else { $this->aSetupSettings['conditionsLink'] = $aTemplateData['conditions']; $sFilename = ($this->sPath != NULL ? $this->sPath : "") . '/klarna/tmpl/' . $this->sType . "_" . strtolower ($this->sCountryCode) . ".html"; } } Klarna::printDebug (__METHOD__ . 'loading template', $sFilename); return file_get_contents ($sFilename); } /** * Fetch the PClasses from file * * @param integer $iSum The sum of the objects to be bought * @param integer $iFlag The KlarnaFlag to be used. Either Checkout or ProductPage flag. * @return void */ public function fetchPClasses ($iSum, $iFlag, $aTypes = NULL) { if ($this->oKlarna == NULL) { throw new KlarnaApiException("No klarna class is set.", "1000"); } $aPClasses = array(); $default = NULL; foreach ($this->oKlarna->getPClasses () as $pclass) { if ($aTypes == NULL || in_array ($pclass->getType (), $aTypes)) { $sType = $pclass->getType (); if ($sType != KlarnaPClass::SPECIAL) { if ($iSum < $pclass->getMinAmount ()) { continue; } if ($pclass->getType () == KlarnaPClass::FIXED) { if ($iFlag == KlarnaFlags::PRODUCT_PAGE) { continue; } $iMonthlyCost = -1; } else { $lowest_payment = KlarnaCalc::get_lowest_payment_for_account ($pclass->getCountry ()); $iMonthlyCost = KlarnaCalc::calc_monthly_cost ($iSum, $pclass, $iFlag); if ($iMonthlyCost < 0.01) { continue; } if ($iFlag == KlarnaFlags::CHECKOUT_PAGE && $pclass->getType () == KlarnaPClass::ACCOUNT && $iMonthlyCost < $lowest_payment) { $iMonthlyCost = $lowest_payment; } if ($pclass->getType () == KlarnaPClass::CAMPAIGN && $iMonthlyCost < $lowest_payment) { continue; } } } else { $iMonthlyCost = -1; } if ($this->sType == 'part') { if ($sType == KlarnaPClass::ACCOUNT) { $default = $pclass; } else { if ($sType == KlarnaPClass::CAMPAIGN) { if ($default === NULL || $default->getType () != KlarnaPClass::ACCOUNT) { $default = $pclass; } } else { if ($sType == KlarnaPClass::FIXED) { if ($default === NULL) { $default = $pclass; } } else { continue; } } } } else { if ($this->sType == 'spec') { if ($sType != KlarnaPClass::SPECIAL) { continue; } $default = $pclass; } } $aPClasses[$pclass->getId ()]['pclass'] = $pclass; $aPClasses[$pclass->getId ()]['monthlyCost'] = $iMonthlyCost; $aPClasses[$pclass->getId ()]['default'] = FALSE; } } if ($default !== NULL) { $aPClasses[$default->getId ()]['default'] = TRUE; } $this->aPClasses = $aPClasses; } /** * Checks whether the country code is accepted by the API * * @throws KlarnaApiException * @param string $sCountryCode The country code ISO-2 * @return boolean */ private function validateCountry ($sCountryCode) { if (in_array (strtolower ($sCountryCode), array("nl", "se", "de", "dk", "no", "fi"))) { $this->sCountryCode = strtolower ($sCountryCode); switch ($this->sCountryCode) { case "nl": $this->iKlarnaCountry = KlarnaCountry::NL; $this->iKlarnaCurrency = KlarnaCurrency::EUR; break; case "se": $this->iKlarnaCountry = KlarnaCountry::SE; $this->iKlarnaCurrency = KlarnaCurrency::SEK; break; case "de": $this->iKlarnaCountry = KlarnaCountry::DE; $this->iKlarnaCurrency = KlarnaCurrency::EUR; break; case "dk": $this->iKlarnaCountry = KlarnaCountry::DK; $this->iKlarnaCurrency = KlarnaCurrency::DKK; break; case "no": $this->iKlarnaCountry = KlarnaCountry::NO; $this->iKlarnaCurrency = KlarnaCurrency::NOK; break; case "fi": $this->iKlarnaCountry = KlarnaCountry::FI; $this->iKlarnaCurrency = KlarnaCurrency::EUR; break; default: break; } return TRUE; } else { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid country code submitted!'); } } /** * Checks whether the country code is accepted by the API * * @throws KlarnaApiException * @param string $sType The type. Either "part", "spec" or "invoice" * @return boolean */ private function validateType ($sType) { if (in_array (strtolower ($sType), array("part", "invoice", "spec"))) { $this->sType = strtolower ($sType); return TRUE; } else { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid type submitted!'); } } /** * Sets the active country from a ISO country string * or a KlarnaCountry constant */ public function setCountry ($country) { if (!is_numeric ($country)) { $country = KlarnaCountry::fromCode ($country); } else { $country = intval ($country); } if ($this->oKlarna == NULL) { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Klarna instance not set'); } $this->iKlarnaCountry = $country; $this->iKlarnaCurrency = $this->oKlarna->getCurrencyForCountry ($country); $this->sCountryCode = $this->oKlarna->getCountryCode ($country); } public function getCountry () { return $this->iKlarnaCountry; } /** * Sets the active country from a ISO country string * or a KlarnaLanguage constant */ public function setLanguage ($language) { if (!is_numeric ($language)) { $language = Klarna::getLanguageForCode ($language); } else { $language = intval ($language); } $this->iKlarnaLanguage = $language; if ($this->oKlarna == NULL) { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Klarna instance not set'); } $this->sLangISO = $this->oKlarna->getLanguageCode ($language); } public function getLanguage () { return $this->iKlarnaLanguage; } /** * Checks whether the country code is accepted by the API * * @throws KlarnaApiException * @param string $a_sLangISO The language in ISO-2 format * @return boolean * @deprecated */ private function validateLangISO ($a_sLangISO) { if (in_array (strtolower ($a_sLangISO), array("sv", "da", "en", "de", "nl", "nb", "fi"))) { $this->sLangISO = strtolower ($a_sLangISO); switch ($this->sLangISO) { case "sv": $this->iKlarnaLanguage = KlarnaLanguage::SV; break; case "da": $this->iKlarnaLanguage = KlarnaLanguage::DA; break; case "de": $this->iKlarnaLanguage = KlarnaLanguage::DE; break; case "nl": $this->iKlarnaLanguage = KlarnaLanguage::NL; break; case "nb": $this->iKlarnaLanguage = KlarnaLanguage::NB; break; case "fi": $this->iKlarnaLanguage = KlarnaLanguage::FI; break; default: break; } return TRUE; } else { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid language (' . $a_sLangISO . ') ISO submitted!'); } } /** * Translating the fetched HTML agains dynamic values set in this class * * @param string $sHtml The HTML to translate * @return string */ private function translateInputFields ($sHtml) { $sHtml = preg_replace_callback ("@{{(.*?)}}@", array($this, 'changeText'), $sHtml); return $sHtml; } /** * Changing the text from a HTML {{VALUE}} to the actual value decided by the array * * @param array $aText The result from the match in function translateInputFields * @return mixed * @deprecated */ private function changeText ($aText) { // Split them $aExplode = explode (".", $aText[1]); $sType = $aExplode[0]; $sName = @$aExplode[1]; if ($sType == "input") { if (array_key_exists ($sName, $this->aInputParameters)) { return $this->aInputParameters[$sName]; } else { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid inputfield value (' . $sName . ') found in HTML code!'); } } else { if ($sType == "lang") { return JText::_ ('VMPAYMENT_KLARNA_' . strtoupper ($sName)); //$this->fetchFromLanguagePack($sName); } else { if ($sType == "setup") { if ($sName == "pclasses") { return $this->renderPClasses (); } if ($sName == 'threatmetrix') { if (!array_key_exists ('threatmetrix', $this->aSetupSettings)) { $this->aSetupSettings['threatmetrix'] = $this->oKlarna-> checkoutHTML (); } return @$this->aSetupSettings['threatmetrix']; } if ($sName == 'additional_information') { $key = @$this->aSetupSettings['additional_information']; $key = 'VMPAYMENT_KLARNA_' . strtoupper ($key); $lang = JFactory::getLanguage (); if ($lang->hasKey ($key)) { $frmt = @JText::_ ($key); //$this->fetchFromLanguagePack($key); return @$this->translateInputFields ($frmt); } else { return ''; } } return @$this->aSetupSettings[$sName]; } else { if ($sType == "value") { return (@$this->aInputValues[$sName]); } else { throw new KlarnaApiException('Error in ' . __METHOD__ . ': Invalid field name (' . $sType . ') found in HTML code!'); } } } } } /** * Redender the PClasses to HTML * * @deprecated * * @return string */ public function renderPClasses () { $sString = ''; foreach ($this->aPClasses as $sPClassId => $aPClassData) { $value = $this->getPresentableValuta ($aPClassData['monthlyCost']); $pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH'); $sString .= '
  • ' . $aPClassData['pclass']->getDescription () . ($aPClassData['monthlyCost'] > 0 ? " - $value $pm" : '') . ($aPClassData['default'] ? 'Chosen' : '') . '
    ' . $sPClassId . '
  • '; } return $sString; } /** * Redender the PClasses to HTML * * @return string */ public function getPClassesInfo () { $pClasses = array(); $i = 0; foreach ($this->aPClasses as $sPClassId => $aPClassData) { $value = $this->getPresentableValuta ($aPClassData['monthlyCost']); $pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH'); $pClasses[$i]['class'] = $aPClassData['default'] ? 'id="click"' : ""; $sString = $aPClassData['pclass']->getDescription () . ($aPClassData['monthlyCost'] > 0 ? " - $value $pm" : '') . ($aPClassData['default'] ? 'Chosen' : ''); $pClasses[$i]['string'] = $sString; $pClasses[$i]['classId'] = $sPClassId; $i++; } return $pClasses; } /** * Redender the PClasses to HTML * * @return string */ public function renderPClass ($pid) { $sString = ""; foreach ($this->aPClasses as $sPClassId => $aPClassData) { if ($aPClassData['pclass']->getId () == $pid) { $value = $this->getPresentableValuta ($aPClassData['monthlyCost']); $pm = JText::_ ('VMPAYMENT_KLARNA_PER_MONTH'); $sString .= $aPClassData['pclass']->getDescription () . ($aPClassData['monthlyCost'] > 0 ? " - $value $pm" : ''); return $sString; } } return $sString; } /** * Make the sum shown presentable * * @param integer $iSum The sum to present * @return string */ /* private */ function getPresentableValuta ($iSum) { $sBefore = ""; $sAfter = ""; switch (strtolower($this->sCountryCode)) { case 'se': $sAfter = " kr"; break; case 'no': $sAfter = " NOK"; break; case 'dk': $sAfter = " DKK"; break; case 'fi'; $sBefore = "EUR"; break; case 'de'; case 'nl'; $sBefore = "€"; break; } return $sBefore . $iSum . $sAfter; } public function setCurrency ($currency) { if (!is_numeric ($currency)) { $currency = KlarnaCurrency::fromCode ($currency); } else { $currency = intval ($currency); } switch ($currency) { case KlarnaCurrency::SEK: case KlarnaCurrency::NOK: case KlarnaCurrency::DKK: $this->addSetupValue ('currency_suffix', ' kr'); $this->addSetupValue ('currency_prefix', ''); break; case KlarnaCurrency::EUR: $this->addSetupValue ('currency_prefix', '€'); $this->addSetupValue ('currency_suffix', ''); break; default: $this->addSetupValue ('currency_suffix', ''); $this->addSetupValue ('currency_prefix', ''); break; } } /** * Fetch data from the language pack * * @param string $sText The text to fech * @param null $sISO * @param null $sPath * @return string * @deprecated */ public function fetchFromLanguagePack ($sText, $sISO = NULL, $sPath = NULL) { if ($sISO == NULL) { if ($this != NULL && $this->sLangISO != NULL) { $sISO = strtolower ($this->sLangISO); } else { $sISO = KlarnaAPI::getISOCode (); } } else { $sISO = KlarnaAPI::getISOCode ($sISO); } if ($this->sPath != NULL) { $sPath = $this->sPath; } if ($this->languagePack == NULL) { $this->languagePack = new KlarnaLanguagePack(JPATH_VMKLARNAPLUGIN . '/klarna/language/klarna_language.xml'); } return $this->languagePack->fetch ($sText, $sISO); } /** * Returns the country code for the set country constant. * * @return string */ public function getISOCode ($sCode = NULL) { switch (strtolower ($sCode)) { case "se": case "sv": return "sv"; case "no": case "nb": return "nb"; case "dk": case "da": return "da"; case "fi": return "fi"; case "de": return "de"; case "nl": return "nl"; case "us": case "uk": case "en": default: return "en"; } } public function displayError ($message, $field = NULL) { // Append message if (array_key_exists ('red_baloon_content', $this->aSetupSettings)) { $this->aSetupSettings['red_baloon_content'] = $this->aSetupSettings['red_baloon_content'] . '
    ' . $message; } else { $this->aSetupSettings['red_baloon_content'] = $message; } // fall back to logo on multiple messages if (array_key_exists ('red_baloon_paymentBox', $this->aSetupSettings)) { $this->aSetupSettings['red_baloon_paymentBox'] = ''; } else { $this->aSetupSettings['red_baloon_paymentBox'] = $field; } } /** * * @param $address * @return */ public static function splitAddress ($address) { $numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $characters = array( '-', '/', ' ', '#', '.', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); $specialchars = array('-', '/', ' ', '#', '.'); //Where do the numbers start? Allow for leading numbers $numpos = self::strpos_arr ($address, $numbers, 2); //Get the streetname by splitting off the from the start of the numbers $streetname = substr ($address, 0, $numpos); //Strip off spaces at the end $streetname = trim ($streetname); //Get the housenumber+extension $numberpart = substr ($address, $numpos); //and strip off spaces $numberpart = trim ($numberpart); //Get the start position of the extension $extpos = self::strpos_arr ($numberpart, $characters, 0); //See if there is one, if so if ($extpos != '') { //get the housenumber $housenumber = substr ($numberpart, 0, $extpos); // and the extension $houseextension = substr ($numberpart, $extpos); // and strip special characters from it $houseextension = str_replace ($specialchars, '', $houseextension); } else { //Otherwise, we already have the housenumber $housenumber = $numberpart; } return array($streetname, $housenumber, $houseextension); } /** * * @param $haystack * @param $needle * @param $where * @return */ private static function strpos_arr ($haystack, $needle, $where) { $defpos = 10000; if (!is_array ($needle)) { $needle = array($needle); } foreach ($needle as $what) { if (($pos = strpos ($haystack, $what, $where)) !== FALSE) { if ($pos < $defpos) { $defpos = $pos; } } } return $defpos; } public function setAddress (KlarnaAddr $addr) { if (!$addr instanceof KlarnaAddr) { throw new KlarnaApiException(__METHOD__ . ': must be passed a KlarnaAddr'); } $reference = @($addr->getFirstName () . ' ' . $addr->getLastName ()); $cellno = $addr->getCellno (); $telno = $addr->getTelno (); $phone = (strlen ($cellno) > 0) ? $cellno : $telno; $values = &$this->aInputValues; $values['firstName'] = $addr->getFirstName (); $values['lastName'] = $addr->getLastName (); $values['phoneNumber'] = $phone; $values['zipcode'] = $addr->getZipCode (); $values['city'] = $addr->getCity (); $values['street'] = $addr->getStreet (); $values['homenumber'] = $addr->getHouseNumber (); $values['house_extension'] = $addr->getHouseExt (); $values['reference'] = $reference; } /** * Given a ISO 8601 date string (YYYY-MM-DD) sets birth_year, birth_month * and birth_day */ public function setBirthday ($dob) { $splitbday = explode ('-', $dob); $values['birth_year'] = @$splitbday[0]; $values['birth_month'] = @$splitbday[1]; $values['birth_day'] = @$splitbday[2]; } } /** * KlarnaApiException class, only used so it says "KlarnaApiException" instead of Exception. * * @package Klarna Standard Kassa API * @author Paul Peelen * @version 1.0 * @since 1.0 - 14 mar 2011 * @link http://integration.klarna.com/ * @copyright Copyright (c) 2011 Klarna AB (http://klarna.com) */ class KlarnaApiException extends Exception { public function __construct ($sMessage, $code = 0) { parent::__construct ($sMessage, $code); } public function __toString () { return __CLASS__ . ":

    [Error: {$this->code}]: {$this->message}

    \n"; } } klarna/klarna/helpers/klarna_payments.php000066600000027712151372777310014661 0ustar00shipTo = $shipTo; $this->country = $cData['country_code']; $this->country_code_3 = $cData['country_code_3']; $this->currency = $cData['currency_code']; $this->virtuemart_currency_id = $cData['virtuemart_currency_id']; //$this->currency = $vendor_currency; // Get EID and Secret $this->eid = $cData['eid']; $this->secret = $cData['secret']; $this->lang = $cData['language_code']; // Is Invoice enabled? $this->enabled = TRUE; // Set modes $this->mode = $cData['mode']; $this->ssl = KlarnaHandler::getKlarnaSSL ($this->mode); $this->web_root = JURI::base (); try { $this->klarna = new Klarna_virtuemart(); $this->klarna->config ($this->eid, $this->secret, $this->country, $this->lang, $this->currency, $this->mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $this->ssl); } catch (Exception $e) { VmError ('klarna_payments', $e); unset($this->klarna); } } /** * Attempt to fill in some of what we've already filled in if we * come back after failing a purchase. */ private function setPreviouslyFilledIn ($klarna_data) { if (($this->country == "nl" ) && isset($klarna_data['pno'])) { $pno = $klarna_data['pno']; $this->klarna_bday['year'] = substr ($pno, 4, 4); $this->klarna_bday['month'] = substr ($pno, 2, 2); $this->klarna_bday['day'] = substr ($pno, 0, 2); } elseif ( $this->country == "de") { $pno = $klarna_data['pno']; $this->klarna_bday['year'] = $klarna_data['birth_year']; $this->klarna_bday['month'] = $klarna_data['birth_month']; $this->klarna_bday['day'] = $klarna_data['birth_day']; } else { $this->socialNumber=$klarna_data['socialNumber']; } $this->klarna_street = ((isset($klarna_data['street']) && !isset($this->klarna_street)) ? $klarna_data['street'] : $this->klarna_street); $this->klarna_houseNr = ((isset($klarna_data['house_no']) && !isset($this->klarna_houseNr)) ? $klarna_data['house_no'] : $this->klarna_houseNr); $this->klarna_houseExt = ((isset($klarna_data['house_ext']) && !isset($this->klarna_houseExt)) ? $klarna_data['house_ext'] : $this->klarna_houseExt); $this->klarna_gender = ((isset($klarna_data['gender']) && !isset($this->klarna_gender)) ? $klarna_data['gender'] : $this->klarna_gender); $this->klarna_year_salary = ((isset($klarna_data['year_salary']) && !isset($this->klarna_year_salary)) ? $klarna_data['year_salary'] : $this->klarna_year_salary); } /** * Build the Payment params */ public function get_payment_params ($method, $payment_type, $cart = NULL, $country_currency_code = '', $vendor_currency='') { if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } if (!class_exists ('KlarnaAPI')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php'); } $payment_params = array(); $invoice_fee = 0; if (!isset($this->klarna) || !($this->klarna instanceof Klarna_virtuemart)) { return NULL; } $payment_params['payment_currency_info'] = ""; if ($cart->pricesCurrency != $this->virtuemart_currency_id) { $payment_params['payment_currency_info'] = JText::_ ('VMPAYMENT_KLARNA_PAYMENT_CURRENCY_INFO'); } if ($payment_type == 'invoice') { KlarnaHandler::getInvoiceFeeInclTax ($method, $this->country_code_3, $cart->pricesCurrency, $this->virtuemart_currency_id, $display_invoice_fee, $invoice_fee); $billTotalInCountryCurrency = 0; $aTypes = NULL; $payment_params['pClasses'] = NULL; } else { $display_fee = 0; $billTotalInCountryCurrency = 0; if (isset($cart->pricesUnformatted['billTotal'])) { $billTotalInCountryCurrency = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $vendor_currency, $country_currency_code, $cart->pricesCurrency); } if ($billTotalInCountryCurrency <= 0) { return NULL; } //$aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN, KlarnaPClass::FIXED); $aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN); } $payment_params['sType'] = $payment_type; $kCheckout = new KlarnaAPI($this->country, $this->lang, $payment_type, $billTotalInCountryCurrency, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, $aTypes, JPATH_VMKLARNAPLUGIN); if ($payment_type == 'invoice') { if ($invoice_fee) { $payment_params['module'] = JText::sprintf ('VMPAYMENT_KLARNA_INVOICE_TITLE', $display_invoice_fee); } else { $payment_params['module'] = JText::_ ('VMPAYMENT_KLARNA_INVOICE_TITLE_NO_PRICE'); } $payment_params['pClasses'] = NULL; $payment_params['id'] = 'klarna_invoice'; } elseif ($payment_type == 'part') { KlarnaHandler::getCheapestPclass ($kCheckout, $cheapest, $minimum); if ($billTotalInCountryCurrency < $minimum) { return NULL; } if (!class_exists ('VirtueMartModelCurrency')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php'); } // Cheapest is in the Klarna country currency, convert it to the current currency display //$currencyDisplay = CurrencyDisplay::getInstance( ); //$countryCurrencyId = $this->virtuemart_currency_id; //$sFee = $currencyDisplay->priceDisplay($cheapest, 0, 1,false); $sFee = $kCheckout->getPresentableValuta ($cheapest); $payment_params['module'] = JText::sprintf ('VMPAYMENT_KLARNA_PARTPAY_TITLE', $sFee); $payment_params['pClasses'] = $kCheckout->getPClassesInfo (); $payment_params['id'] = 'klarna_partPayment'; } else { $pclasses = $kCheckout->aPClasses; if (empty($pclasses)) { return NULL; } $payment_params['module'] = JText::_ ('VMPAYMENT_KLARNA_SPEC_TITLE'); $payment_params['pClasses'] = $kCheckout->getPClassesInfo (); $payment_params['id'] = 'klarna_SpecCamp'; } $payment_params['payment_link'] = "https://online.klarna.com/villkor.yaws?eid=" . $this->eid . "&charge=" . $invoice_fee; if (strtolower ($this->country) == 'de') { $vendor_id = 1; $payment_params['agb_link'] = JRoute::_ ('index.php?option=com_virtuemart&view=vendor&layout=tos&virtuemart_vendor_id=' . $vendor_id); } //$lang = KlarnaHandler::getLanguageForCountry($method, $this->country); $symbol = KlarnaHandler::getCurrencySymbolForCountry ($method, $this->country); if (KlarnaHandler::getKlarnaError ($klarnaError, $klarnaOption)) { if ($klarnaOption == 'klarna_' . $payment_type) { $payment_params['red_baloon_content'] = $klarnaError; $payment_params['red_baloon_paymentBox'] = 'klarna_box_' . $klarnaOption; //KlarnaHandler::clearKlarnaError (); } } // Something went wrong, refill what we can. $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if (!empty($sessionKlarna)) { $sessionKlarnaData = unserialize ($sessionKlarna); if (isset($sessionKlarnaData->KLARNA_DATA)) { $klarnaData = $sessionKlarnaData->KLARNA_DATA; $this->setPreviouslyFilledIn ($klarnaData); } } $payment_params['paymentPlan'] = ''; if (is_array ($kCheckout->aPClasses)) { foreach ($kCheckout->aPClasses as $pclass) { if ($pclass['default'] === TRUE) { $payment_params['paymentPlan'] = $pclass['pclass']->getId (); break; } } } if ($payment_type != "spec") { //$payment_params['conditionsLink'] = $aTemplateData['conditions']; } $payment_params['fields'] = $this->shipTo; $payment_params['payment_id'] = 'virtuemart_paymentmethod_id'; $payment_params['checkout'] = $this->klarna->checkoutHTML (); $payment_params['eid'] = $this->eid; $payment_params['year_salary'] = $this->klarna_year_salary; $payment_params['agreement_link'] = $this->payment_charge_link; $payment_params['sum'] = $invoice_fee; $payment_params['fee'] = $invoice_fee; $payment_params['invoice_fee'] = $invoice_fee; $payment_params['langISO'] = $this->lang; $payment_params['countryCode'] = $this->country; $payment_params['flag'] = KlarnaFlags::CHECKOUT_PAGE; $payment_params['payment_id'] = "payment"; $payment_params['invoice_name'] = 'klarna_invoice'; $payment_params['part_name'] = 'klarna_partPayment'; $payment_params['spec_name'] = 'klarna_SpecCamp'; $payment_params['fields']['socialNumber'] = isset($this->socialNumber)?$this->socialNumber:""; return $payment_params; } /** * Build the Payment params */ public function getCheapestMonthlyCost ($cart = NULL, $cData) { if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } if (!class_exists ('KlarnaAPI')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php'); } if (!isset($this->klarna) || !($this->klarna instanceof Klarna_virtuemart)) { return NULL; } $display_fee = 0; $billTotalInCountryCurrency = 0; if (isset($cart->pricesUnformatted['billTotal'])) { $billTotalInCountryCurrency = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $cData['vendor_currency'], $cData['virtuemart_currency_id'], $cart->pricesCurrency); } if ($billTotalInCountryCurrency <= 0) { return NULL; } $aTypes = array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN); $kCheckout = new KlarnaAPI($this->country, $this->lang, 'part', $billTotalInCountryCurrency, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, $aTypes, JPATH_VMKLARNAPLUGIN); KlarnaHandler::getCheapestPclass ($kCheckout, $cheapest, $minimum); vmdebug('getCheapestMonthlyCost',$cart->pricesUnformatted['billTotal'], $billTotalInCountryCurrency , $cheapest,$minimum); if ($billTotalInCountryCurrency < $minimum) { return NULL; } if (!class_exists ('VirtueMartModelCurrency')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php'); } $sFee = $kCheckout->getPresentableValuta ($cheapest); return $sFee; } /** * @return string */ public function getTermsLink () { return 'https://static.klarna.com/external/html/' . KLARNA_SPECIAL_CAMPAIGN . '_' . strtolower ($this->country) . '.html'; } /** * @param $pid * @param $totalSum * @return string */ function displayPclass ($pid, $totalSum) { if (!class_exists ('KlarnaAPI')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php'); } $kCheckout = new KlarnaAPI($this->country, $this->lang, 'part', $totalSum, KlarnaFlags::CHECKOUT_PAGE, $this->klarna, array(KlarnaPClass::ACCOUNT, KlarnaPClass::CAMPAIGN, KlarnaPClass::FIXED), JPATH_VMKLARNAPLUGIN); return $kCheckout->renderPClass ($pid); } } klarna/klarna/helpers/index.html000066600000000057151372777310012746 0ustar00 klarna/klarna/helpers/klarna_virtuemart.php000066600000001717151372777310015220 0ustar00VERSION = 'PHP'.phpversion().':2.0.26d'; Klarna::$debug = false; } } klarna/klarna/helpers/klarna_productprice.php000066600000013466151372777310015525 0ustar00path = JPATH_VMKLARNAPLUGIN . '/klarna/'; if (!class_exists ('ShopFunctions')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php'); } $this->cData = $cData; //$this->currencyId = ShopFunctions::getCurrencyIDByName($this->cData['currency_code']); //vmdebug ('klarna_productPrice', $this->cData); try { $this->klarna_virtuemart = new Klarna_virtuemart(); $this->klarna_virtuemart->config ($this->cData['eid'], $this->cData['secret'], $this->cData['country'], $this->cData['language'], $this->cData['currency'], $this->cData['mode'], VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), FALSE); } catch (Exception $e) { vmDebug ('klarna_productPrice', $e->getMessage (), $e->getFile() , $e->getLine(), $this->cData); vmError ('klarna_productPrice', 'klarna_productPrice: '.$e->getMessage (). " country:".$this->cData['country_code_3'] ); unset($this->klarna); } } /** * @param $product * @return bool */ private function showPP ($product, $cart) { if (!isset($this->klarna_virtuemart) || !($this->klarna_virtuemart instanceof Klarna_virtuemart)) { return FALSE; } if (!VMKLARNA_SHOW_PRODUCTPRICE) { vmDebug ('Klarna: showPP', 'dont show price because VMKLARNA_SHOW_PRODUCTPRICE'); return FALSE; } // the price is in the vendor currency // convert price in NLD currency= euro $price = KlarnaHandler::convertPrice ($product->prices['salesPrice'], $this->cData['vendor_currency'], 'EUR', $cart->pricesCurrency); if (strtolower ($this->cData['country_code']) == 'nl' && !KlarnaHandler::checkNLpriceCondition ($price )) { vmDebug ('showPP', 'dont show price for NL', $this->cData['country_code'], $price); return FALSE; } if ($price <= $this->cData['min_amount'] AND !empty($this->cData['min_amount'])) { return FALSE; } return TRUE; } /** * @param $product * @return array|null */ public function showProductPrice ($product, $cart) { if (!$this->showPP ($product, $cart)) { return NULL; } $viewData = $this->getViewData ($product); return $viewData; } /** * @param $product * @return array|null */ private function getViewData ($product) { if (!class_exists ('KlarnaAPI')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'helpers' . DS . 'klarnaapi.php'); } if (!class_exists ('VirtueMartModelCurrency')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'currency.php'); } $price = $product->prices['salesPrice']; $country = $this->cData['country']; $lang = $this->cData['language_code']; $types = array(KlarnaPClass::CAMPAIGN, KlarnaPClass::ACCOUNT, KlarnaPClass::FIXED); try { $kCheckout = new KlarnaAPI($country, $lang, 'part', $price, KlarnaFlags::PRODUCT_PAGE, $this->klarna_virtuemart, $types, $this->path); } catch(Exception $e) { VmDebug('getViewData','Error in ' . __METHOD__ . ': ' . $e->getMessage(), $e->getCode()); VmError( $e->getMessage(), 'getViewData'.'Error in ' . __METHOD__ . ': ' . $e->getMessage(), $e->getCode()); return NULL; } $kCheckout->setCurrency ($this->cData['currency']); // TODO : Not top to get setup values here! $this->settings = $kCheckout->getSetupValues (); if ($price > 0 && count ($kCheckout->aPClasses) > 0) { $currencydisplay = CurrencyDisplay::getInstance (); $sMonthDefault = NULL; $sTableHtml = ""; $monthTable = array(); // either in vendor's currency, or shipTo Currency $countryCurrencyId = $this->cData['virtuemart_currency_id']; $currency = CurrencyDisplay::getInstance ($countryCurrencyId); $fromCurrency = $currency->getCurrencyForDisplay (); //$paymentCurrency = CurrencyDisplay::getInstance($this->cart->paymentCurrency); //$totalInPaymentCurrency = $paymentCurrency->priceDisplay( $this->cart->pricesUnformatted['billTotal'],$this->cart->paymentCurrency) ; //$currencyDisplay = CurrencyDisplay::getInstance($this->cart->pricesCurrency); $i = 0; foreach ($kCheckout->aPClasses as $pclass) { if ($sMonthDefault === NULL || $pclass['monthlyCost'] < $sMonthDefault) { $sMonthDefault = $currency->priceDisplay ($pclass['monthlyCost'], $countryCurrencyId); } if ($pclass['pclass']->getType () == KlarnaPClass::ACCOUNT) { $pp_title = JText::_ ('VMPAYMENT_KLARNA_PPBOX_ACCOUNT'); } else { $pp_title = $pclass['pclass']->getMonths () . " " . JText::_ ('VMPAYMENT_KLARNA_PPBOX_TH_MONTH'); } $pp_price = $currency->priceDisplay ($pclass['monthlyCost'], $countryCurrencyId); $monthTable[$i] = array( 'pp_title' => html_entity_decode ($pp_title), 'pp_price' => $pp_price, 'country' => $country); $i++; } $cd = CurrencyDisplay::getInstance ($fromCurrency); $aInputValues = array(); $aInputValues['defaultMonth'] = $sMonthDefault; $aInputValues['monthTable'] = $monthTable; $aInputValues['eid'] = $this->cData['eid']; $aInputValues['country'] = KlarnaCountry::getCode ($country); if ($country == KlarnaCountry::DE) { $aInputValues['asterisk'] = '*'; } else { $aInputValues['asterisk'] = ''; } return $aInputValues; } return NULL; } } klarna/klarna/helpers/.htaccess000066600000000177151372777310012552 0ustar00 Order allow,deny Deny from all klarna/klarna/helpers/impl.klarna_mobile.php000066600000021617151372777310015226 0ustar00oKlarna = &$oKlarna; $this->sTemplate = $sTemplate; $this->sPath = $sPath; $this->sCountryCode = $sCountry; $this->sLangISO = 'sv'; } /** * Fetches the product and adds it as an article to the klarna class. No need to return any data. * Articles need to be set for fraud purpose, incorrect article means no_risk invoice. Hereby klarna will not take any risks. * * @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality * @param Klarna $oKlarna The Klarna class object. Used to set any articles * @return void */ abstract protected function fetchProduct($mProductId); /** * When a purchase is made, the script returns an redirect-URL or a message. When the URL is returned, the user is re-directed to this page. * This could be an URL to a downloadable file (WARNING! SHOULD ALWAYS BE A DYNAMIC URL!), or a link to a "Thank you"/confirmation page (Comon for donation purposes) * * @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality * @return mixed Either NULL or FALSE if no URL is available, or STRING with full URL when URL is available. */ abstract protected function fetchRedirectUrl ($mProductId); /** * When a purchase is made (approved as well) it might needs to be added to the merchants order system. In this function you can define how the order of a product should be handled. * * @param mixed $mProductId The product identified. Either int or string. Adapted according shop functionality * @param integer $iKlarnaReference The reference returned by Klarna * @param string $sTelNo The telephone number used to make a purchase * @return void */ abstract protected function processOrder ($mProductId, $iKlarnaReference, $iTelNo); /** * Fetch the HTML from the template theme * * @return string The HTML completed as string */ public function retrieveHTML () { // Get template $sTemplate = ($this->sPath != null ? $this->sPath : "") . '/html/mobile/' . $this->sTemplate . "/" . strtolower($this->sCountryCode) . "/template.html"; return $this->translateInputFields(file_get_contents($sTemplate)); } /** * Adding an input value * * @param string $sParamName The name of an paramteter to set * @param mixed $mParamValue The value of the parameter * @return void */ public function addInput ($sParamName, $mParamValue) { $this->aInputParameters[$sParamName] = $mParamValue; } /** * Translating the fetched HTML agains dynamic values set in this class * * @param string $sHtml The HTML to translate * @return string */ private function translateInputFields ($sHtml) { $sHtml = preg_replace_callback("@{{(.*?)}}@", array($this, 'changeText'), $sHtml); return $sHtml; } /** * Changeing the text from a HTML {{VALUE}} to the acual value decided by the array * * @param array $aText The result from the match in function translateInputFields * @return mixed */ private function changeText ($aText) { // Split them $aExplode = explode(".", $aText[1]); $sType = $aExplode[0]; $sName = $aExplode[1]; if ($sType == "input") { if (array_key_exists($sName, $this->aInputParameters)) return $this->aInputParameters[$sName]; else { throw new KlarnaMobileApiException('Error in ' . __METHOD__ . ': Invalid inputfield value ('.$sName.') found in HTML code!'); return false; } } else if($sType == "lang") { return JText::_($sName); //$this->fetchFromLanguagePack($sName); } else if($sType == "setup") { return @$this->aSetupSettings[$sName]; } else if ($sType == "value") { return @$this->aInputValues[$sName]; } else { throw new KlarnaMobileApiException('Error in ' . __METHOD__ . ': Invalid field name ('.$sType.') found in HTML code!'); return false; } } /** * Fetch data from the language pack * * @param string $sText The text to fech * @return string */ public function fetchFromLanguagePack ($sText) { if ($this != null && $this->sLangISO != null) $sISO = strtolower($this->sLangISO); else $sISO = KlarnaAPI::getISOCode(); $oXml = simplexml_load_file($this->sPath . '/klarna_files/klarna_language.xml'); $aResult= (array)@$oXml->xpath("//string[@id='$sText']/$sISO"); $aResult= (array)@$aResult[0]; return @$aResult[0]; } /** * Request the code for the mobile phone * * @param string $sTelNo The telephone number * @param int $iSum The sum to request * @return mixed BOOLEAN true if success, message or exception if error */ public function requestCode ($iPid, $sTelNo) { $this->sTelNo = $sTelNo; try { $this->fetchProduct($iPid); //Transmit all the specified data, from the steps above, to Klarna. $aResult = $this->oKlarna->reserveAmount( $this->sTelNo, null, $this->iSum, KlarnaFlags::RSRV_PHONE_TRANSACTION+KlarnaFlags::RSRV_SEND_PHONE_PIN, -1 ); return $this->translateSuccesToXml($aResult[0], $aResult[1]); } catch(Exception $e) { return $this->translateErrorToXML($e->getCode(), utf8_encode($e->getMessage())); } } /** * Request the code for the mobile phone * * @param string $sTelNo The telephone number * @param int $iSum The sum to request * @return mixed BOOLEAN true if success, message or exception if error */ public function makePurchase ($iPid, $sTelNo, $sPinCode, $iRefNo) { $this->sTelNo = $sTelNo; try { $this->fetchProduct($iPid); $this->oKlarna->setExtraInfo('pin', $sPinCode); $aResult = $this->oKlarna->activateReservation( $this->sTelNo, $iRefNo, null, null, KlarnaFlags::RSRV_PHONE_TRANSACTION+KlarnaFlags::RSRV_SEND_PHONE_PIN, -1 ); $sUrl = $this->fetchRedirectUrl($iPid); $this->processOrder($iPid, $iRefNo, $sTelNo); array_push($aResult, $sUrl); return $aResult; } catch(Exception $e) { return array("-1", utf8_encode($e->getMessage()), $e->getCode()); } } private function translateErrorToXML ($iError, $sErrorMessage) { $sReturn = << -1 $iError $sErrorMessage EOD; return $sReturn; } private function translateSuccesToXml ($iStatusCode, $sMessage) { $sReturn = << $iStatusCode $sMessage EOD; return $sReturn; } } /** * KlarnaMobileApiException class. * * @package Klarna Standard Kassa API * @version 1.0 * @since 1.0 - 14 mar 2011 * @link http://integration.klarna.com/ * @copyright Copyright (c) 2011 Klarna AB (http://klarna.com) */ class KlarnaMobileApiException extends Exception { public function __construct($sMessage, $code=0, Exception $previous = null) { parent::__construct($sMessage,$code, $previous); } public function __toString() { return __CLASS__ . ":

    [Error: {$this->code}]: {$this->message}

    \n"; } }klarna/klarna/helpers/klarna_ajax.php000066600000012060151372777310013732 0ustar00api = $api; $this->eid = $eid; $this->path = $path; $this->coSetup = array(); } /** * @param $template */ public function __setTemplate($template) { if (is_array($template)) { $this->template = array_merge($this->template, $template); } else { $this->template['name'] = $template; } } /** * @param $arr */ public function __addSetupValues($arr) { if (is_array($arr)) { $this->coSetup = array_merge($this->coSetup, $arr); } } /** * @return null * @throws KlarnaApiException */ public function languagepack() { $sSubAction = JRequest::getWord('subAction'); if (!isset($this->template['name']) || $this->template['name'] == '') { $this->template['name'] = "default"; } if ($sSubAction == "klarna_box") { $sNewISO = JRequest::getWord('newIso'); $sCountry = JRequest::getWord('country'); $iSum = JRequest::getFloat('sum', 0); $iInvoiceFee = JRequest::getFloat('fee', 0); $iFlag = JRequest::getInt('flag'); $sType = JRequest::getWord('type'); $aParams = JRequest::getVar('params'); $aValues = JRequest::getVar('values'); // foreach($aValues as $key => $value) { // $aValues[$key] = utf8_encode($value); // } // foreach($aParams as $key => $value) { // $aParams[$key] = utf8_decode($value); // } if ($sType != "part" && $sType != "invoice" && $sType != "spec") { throw new KlarnaApiException("Invalid parameters"); } $this->api->setCountry($sCountry); if ($sType == 'spec') { $types = array(KlarnaPClass::SPECIAL); } else { $types = array(KlarnaPClass::CAMPAIGN, KlarnaPClass::ACCOUNT, KlarnaPClass::FIXED); } $oApi = new KlarnaAPI ($sCountry, $sNewISO, $sType, $iSum, $iFlag, $this->api, $types, VMKLARNAPLUGINWEBROOT); // $oApi->addSetupValue ('web_root', $this->webroot); // $oApi->setPaths (); $oApi->addSetupValue('eid', $this->eid); if ($sType == 'invoice') { $oApi->setInvoiceFee($iInvoiceFee); } $oApi->setCurrency($this->api->getCurrency()); if (count($this->coSetup) > 0) { $oApi->addMultipleSetupValues($this->coSetup); } return $oApi->retrieveLayout($aParams, $aValues); // if ($sType == 'spec') { // return $oApi->retrieveHTML($aParams, $aValues, null, $this->template); // } else { // return $oApi->retrieveHTML ($aParams, $aValues); // } } else { if ($sSubAction == 'jsLanguagePack') { $sNewISO = JRequest::getWord('newIso'); $sFetch = ""; } else { throw new KlarnaApiException("Invalid sub-action"); } } } public function getAddress() { $aSessionCalls = array(); // Check the session for calls if (array_key_exists('klarna_address', $_SESSION)) { $sSessionCalls = base64_decode($_SESSION['klarna_address']); $aSessionCalls = unserialize($sSessionCalls); } $sPNO = JRequest::getWord('socialNumber'); //JRequest::getWord('pno'); $sCountry = strtolower(JRequest::getWord('country')); if (array_key_exists($sPNO, $aSessionCalls)) { $addrs = $aSessionCalls[$sPNO]; } else { $addrs = $this->api->getAddresses($sPNO, NULL, KlarnaFlags::GA_GIVEN); $aSessionCalls[$sPNO] = $addrs; $_SESSION['klarna_address'] = base64_encode(serialize($aSessionCalls)); } $sString = "\n"; //eval breaks at question-mark gt $sString .= "\n"; //This example only works for GA_GIVEN. foreach ($addrs as $index => $addr) { if ($addr->isCompany) { $implode = array( 'companyName' => $addr->getCompanyName(), 'street' => $addr->getStreet(), 'zip' => $addr->getZipCode(), 'city' => $addr->getCity(), 'countryCode' => $addr->getCountryCode() ); } else { $implode = array( 'first_name' => $addr->getFirstName(), 'last_name' => $addr->getLastName(), 'street' => $addr->getStreet(), 'zip' => $addr->getZipCode(), 'city' => $addr->getCity(), 'countryCode' => $addr->getCountryCode() ); } $sString .= "
    \n"; foreach ($implode as $key => $val) { $sString .= "<" . $key . ">" . Klarna::num_htmlentities($val) . "\n"; } $sString .= "
    \n"; } $sString .= "
    "; return array( 'type' => 'text/xml', 'value' => $sString); } } klarna/klarna/helpers/klarnahandler.php000066600000132746151372777310014303 0ustar00 array( 'pno_encoding' => 3, 'language' => 97, 'language_code' => 'nb', 'country' => 164, 'currency' => 1, 'currency_code' => 'NOK', 'currency_symbol' => 'kr', 'country_code' => 'no'), 'SWE' => array( 'pno_encoding' => 2, 'language' => 138, 'language_code' => 'sv', 'country' => 209, 'country_code' => 'se', 'currency' => 0, 'currency_code' => 'SEK', 'currency_symbol' => 'kr'), 'DNK' => array( 'pno_encoding' => 5, 'language' => 27, 'language_code' => 'da', 'country' => 59, 'country_code' => 'dk', 'currency' => 3, 'currency_code' => 'DKK', 'currency_symbol' => 'kr', ), 'FIN' => array( 'pno_encoding' => 4, 'language' => 37, 'language_code' => 'fi', 'country' => 73, 'country_code' => 'fi', 'currency' => 2, 'currency_code' => 'EUR', 'currency_symbol' => '€' ), 'NLD' => array( 'pno_encoding' => 7, 'language' => 101, 'language_code' => 'nl', 'country' => 154, 'country_code' => 'nl', 'currency' => 2, 'currency_code' => 'EUR', 'currency_symbol' => '€', ), 'DEU' => array( 'pno_encoding' => 6, 'language' => 28, 'language_code' => 'de', 'country' => 81, 'country_code' => 'de', 'currency' => 2, 'currency_code' => 'EUR', 'currency_symbol' => '€' )); return $countriesData; } /** * @static * @param $method * @param $country * @return array|null */ static function countryData ($method, $country) { $countriesData = self::countriesData (); $lower_country = strtolower ($country); if (array_key_exists (strtoupper ($country), $countriesData)) { $cData = $countriesData[strtoupper ($country)]; $eid = 'klarna_merchantid_' . $lower_country; $secret = 'klarna_sharedsecret_' . $lower_country; $invoice_fee = 'klarna_invoicefee_' . $lower_country; $min_amount = 'klarna_min_amount_part_' . $lower_country; $payment_activated = 'klarna_payments_' . $lower_country; $active = 'klarna_active_' . $lower_country; $cData['eid'] = $method->$eid; $cData['secret'] = $method->$secret; $cData['invoice_fee'] = (double)$method->$invoice_fee; $cData['country_code_3'] = $country; $cData['virtuemart_currency_id'] = ShopFunctions::getCurrencyIDByName ($cData['currency_code']); $cData['virtuemart_country_id'] = ShopFunctions::getCountryIDByName ($country); $cData['mode'] = KlarnaHandler::getKlarnaMode ($method, $country); $cData['min_amount'] = $method->$min_amount; $cData['active'] = $method->$active; if (empty($method->$payment_activated)){ $method->$payment_activated=array('invoice', 'part'); } $cData['payments_activated'] = $method->$payment_activated; if (!class_exists ('VirtueMartModelVendor')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'); } $vendor_id = 1; $cData['vendor_currency'] = VirtueMartModelVendor::getVendorCurrency ($vendor_id)->vendor_currency; return $cData; } else { return NULL; } } /** * @static * @param $method * @param $country * @return array|null */ public static function getCountryData ($method, $country) { //$country = self::convertToThreeLetterCode($country); return self::countryData ($method, $country); } /** * @static * @param $method * @param $country * @return mixed */ public static function convertCountry ($method, $country) { $country_data = self::countryData ($method, $country); return $country_data['country_code']; } /** * @static * @param $method * @param $country * @return mixed */ public static function getLanguageForCountry ($method, $country) { $country = self::convertToThreeLetterCode ($country); $country_data = self::countryData ($method, $country); return $country_data['language_code']; } /** * @static * @param $method * @param $country * @return mixed */ public static function getCurrencySymbolForCountry ($method, $country) { $country_data = self::countryData ($method, $country); return $country_data['currency_symbol']; } /** * @static * @param $method * @param $country * @return mixed */ public static function getInvoiceFee ($method, $country) { $invoice_fee = 'klarna_invoicefee_' . strtolower ($country); return $method->$invoice_fee; } /** * @static * @param $method * @param $country * @return mixed */ public static function getInvoiceTaxId ($method, $country) { $invoice_fee_tax = 'klarna_invoice_tax_id_' . strtolower ($country); return $method->$invoice_fee_tax; } /** * The invoice fee is in the vendor currency, and should be converted to the payment currency * * @static * @param $method * @param $country * @return mixed */ public static function getInvoiceFeeInclTax ($method, $country, $cartPricesCurrency, $cartPaymentCurrency, &$display_invoice_fee, &$invoice_fee) { $method_invoice_fee = self::getInvoiceFee ($method, $country); $invoice_tax_id = self::getInvoiceTaxId ($method, $country); vmdebug ('getInvoiceFeeInclTax', $cartPaymentCurrency, $invoice_fee); if (!class_exists ('calculationHelper')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php'); } if (!class_exists ('CurrencyDisplay')) { require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'); } if (!class_exists ('VirtueMartModelVendor')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'); } $vendor_id = 1; $vendor_currency = VirtueMartModelVendor::getVendorCurrency ($vendor_id); //$currency = CurrencyDisplay::getInstance (); $paymentCurrency = CurrencyDisplay::getInstance ($cartPaymentCurrency); $invoice_fee = (double)round ($paymentCurrency->convertCurrencyTo ($cartPaymentCurrency, $method_invoice_fee, FALSE), 2); $currencyDisplay = CurrencyDisplay::getInstance ($cartPricesCurrency); $paymentCurrency = CurrencyDisplay::getInstance ($cartPaymentCurrency); $display_invoice_fee = $paymentCurrency->priceDisplay ($method_invoice_fee, $cartPaymentCurrency); $currencyDisplay = CurrencyDisplay::getInstance ($cartPricesCurrency); vmdebug ('getInvoiceFeeInclTax', $cartPaymentCurrency, $invoice_fee, $invoice_tax_id, $display_invoice_fee); return; } /* * @depredecated */ /** * @static * @param $country * @return string */ public static function convertToThreeLetterCode ($country) { switch (strtolower ($country)) { case "se": return "swe"; case "de": return "deu"; case "dk": return "dnk"; case "nl": return "nld"; case "fi": return "fin"; case "no": return "nor"; default: return $country; } } /** * @static * @return array */ public static function getKlarnaCountries () { $klarna_countries = array("swe", "deu", "dnk", "nld", "fin", "nor"); return $klarna_countries; } /** * @static * @return array */ static function getDataFromEditPayment () { VmConfig::loadJLang('com_virtuemart_shoppers', true); $kIndex = 'klarna_'; $klarna['klarna_paymentmethod'] = JRequest::getVar ($kIndex . 'paymentmethod'); if ($klarna['klarna_paymentmethod'] == 'klarna_invoice') { $klarna_option = 'invoice'; } elseif ($klarna['klarna_paymentmethod'] == 'klarna_partPayment') { $klarna_option = 'part'; } elseif ($klarna['klarna_paymentmethod'] == 'klarna_speccamp') { $klarna_option = 'spec'; } else { return NULL; } $prefix=$klarna_option . '_' . $kIndex ; //Removes spaces, tabs, and other delimiters. $klarna['pno'] = preg_replace ('/[ \t\,\.\!\#\;\:\r\n\v\f]/', '', JRequest::getVar ($prefix . 'pnum', '')); $klarna['socialNumber'] = preg_replace ('/[ \t\,\.\!\#\;\:\r\n\v\f]/', '', JRequest::getVar ($prefix . 'socialNumber')); $klarna['phone'] = JRequest::getVar ($prefix . 'phone'); $klarna['email'] = JRequest::getVar ($prefix . 'emailAddress'); $klarna['street'] = JRequest::getVar ($prefix . 'street'); $klarna['house_no'] = JRequest::getVar ($prefix . 'homenumber'); $klarna['house_ext'] = JRequest::getVar ($prefix . 'house_extension'); $klarna['year_salary'] = JRequest::getVar ($prefix . 'ysalary'); $klarna['reference'] = JRequest::getVar ($prefix . 'reference'); $klarna['city'] = JRequest::getVar ($prefix . 'city'); $klarna['zip'] = JRequest::getVar ($prefix . 'zipcode'); $klarna['first_name'] = JRequest::getVar ($prefix . 'firstName'); $klarna['last_name'] = JRequest::getVar ($prefix . 'lastName'); $klarna['invoice_type'] = JRequest::getVar ('klarna_invoice_type'); $klarna['company_name'] = JRequest::getVar ('klarna_company_name'); $klarna['phone'] = JRequest::getVar ($prefix . 'phone'); $klarna['consent'] = JRequest::getVar ($prefix . 'consent'); $klarna['gender'] = JRequest::getVar ($prefix . 'gender'); switch ($klarna['gender']) { case KlarnaFlags::MALE : $klarna['title'] = JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR'); break; case KlarnaFlags::FEMALE: //$this->klarna_gender = KlarnaFlags::FEMALE; $klarna['title'] = JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS'); break; } $klarna['birth_day'] = JRequest::getVar ($prefix . 'birth_day', ''); $klarna['birth_month'] = JRequest::getVar ($prefix . 'birth_month', ''); $klarna['birth_year'] = JRequest::getVar ($prefix . 'birth_year', ''); if (isset($klarna['birth_year']) and !empty($klarna['birth_year'])) { // due to the select list if ($klarna['birth_month'] != 0 and $klarna['birth_month'] != 0) { $klarna['birthday'] = $klarna['birth_year'] . "-" . $klarna['birth_month'] . "-" . $klarna['birth_day']; $klarna['pno_frombirthday'] = JRequest::getVar ($prefix . 'birth_day') . JRequest::getVar ($prefix . 'birth_month') . JRequest::getVar ($prefix . 'birth_year'); } else { $klarna['birthday'] = ''; } } else { $klarna['birthday'] = ''; } return $klarna; } /** * @static * @param $cData * @param $order * @return KlarnaAddr */ private static function getBilling ($cData, $order) { $bt = $order['BT']; $bill_country = shopFunctions::getCountryByID ($bt['virtuemart_country_id'], 'country_2_code'); //$cData = self::countryData($method, $country); $bill_street = $bt['address_1']; $bill_ext = ""; $bill_number = ""; if (strtolower ($bill_country) == "de" || strtolower ($bill_country) == "nl") { $splitAddress = array('', '', ''); $splitAddress = self::splitAddress ($bt['address_1']); $bill_street = $splitAddress[0]; $bill_number = $splitAddress[1]; switch ($bt['title']) { case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR'): //$this->klarna_gender = KlarnaFlags::MALE; break; case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MISS'): case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS'): //$this->klarna_gender = KlarnaFlags::FEMALE; break; default: //$this->klarna_gender = NULL; break; } if (strtolower ($bill_country) == "nl") { $bill_ext = $splitAddress[2]; } } $billing = new KlarnaAddr( $bt['email'], $bt['phone_1'], @$bt['phone_2'], utf8_decode ($bt['first_name']), utf8_decode ($bt['last_name']), '', utf8_decode ($bill_street), $bt['zip'], utf8_decode ($bt['city']), $bill_country, $bill_number, $bill_ext ); return $billing; } /** * @static * @param $method * @param $order * @param $klarna_pclass * @return array|bool * @throws Exception */ public static function addTransaction ($method, $order, $klarna_pclass) { if (!class_exists ('KlarnaAddr')) { require (JPATH_VMKLARNAPLUGIN . DS . 'klarna' . DS . 'api' . DS . 'klarnaaddr.php'); } $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); $sessionKlarnaData = unserialize ($sessionKlarna); if (!isset($sessionKlarnaData)) { throw new Exception("No klarna Session data set"); } $klarnaData = $sessionKlarnaData->KLARNA_DATA; if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) { $shipTo = $order['details']['BT']; } else { $shipTo = (!isset($order['details']['ST']) or empty($order['details']['ST']) or count ($order['details']['ST']) == 0) ? $order['details']['BT'] : $order['details']['ST']; } $billTo = $order['details']['BT']; $country = shopFunctions::getCountrybyID ($shipTo->virtuemart_country_id, 'country_3_code'); $cData = self::countryData ($method, $country); //$total_price_excl_vat = self::convertPrice($order['details']['BT']->order_subtotal, $cData['currency_code']); //$total_price_incl_vat = self::convertPrice($order['details']['BT']->order_subtotal + $order['details']['BT']->order_tax, $cData['currency_code'], $order['details']['BT']->order_currency); $mode = KlarnaHandler::getKlarnaMode ($method, $cData['country_code_3']); $ssl = KlarnaHandler::getKlarnaSSL ($mode); // Instantiate klarna object. $klarna = new Klarna_virtuemart(); $klarna->config ($cData['eid'], $cData['secret'], $cData['country_code'], $cData['language'], $cData['currency_code'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $ssl); // Sets order id's from other systems for the upcoming transaction. $klarna->setEstoreInfo ($order['details']['BT']->order_number); // Fill the good list the we send to Klarna foreach ($order['items'] as $item) { if ($item->product_basePriceWithTax!=0.0) { if ( $item->product_basePriceWithTax != $item->product_final_price) { $price= $item->product_basePriceWithTax; } else { $price= $item->product_final_price; } } else { if ( $item->product_priceWithoutTax != $item->product_item_price) { $price= $item->product_item_price; } else { $price= $item->product_discountedPriceWithoutTax; } } $item_price = self::convertPrice ($price, $order['details']['BT']->order_currency, $cData['currency_code']); $item_price = (double)(round ($item_price, 2)); $item_tax_percent=0; foreach ($order['calc_rules'] as $calc_rule) { if ($calc_rule->virtuemart_order_item_id==$item->virtuemart_order_item_id AND $calc_rule->calc_kind== 'VatTax') { $item_tax_percent=$calc_rule->calc_value; break; } } //$item_discount_percent = (double)(round (abs (($item->product_subtotal_discount / $item->product_quantity) * 100 / $price), 2)); $item_discount_percent=0.0; $discount_tax_percent=0.0; $klarna->addArticle ($item->product_quantity, utf8_decode ($item->order_item_sku), utf8_decode (strip_tags ($item->order_item_name)), $item_price, (double)$item_tax_percent, $item_discount_percent, KlarnaFlags::INC_VAT); $discount_tax_percent=0.0; $includeVat=KlarnaFlags::INC_VAT; if ($item->product_subtotal_discount != 0.0) { if ($item->product_subtotal_discount > 0.0) { $discount_tax_percent=$item_tax_percent; $includeVat=0; } $name=utf8_decode (strip_tags ($item->order_item_name)). ' ('.JText::_('VMPAYMENT_KLARNA_PRODUCTDISCOUNT'). ')'; $discount = self::convertPrice (abs($item->product_subtotal_discount), $order['details']['BT']->order_currency, $cData['currency_code']); $discount = (double)(round (abs($discount), 2)) * -1 ; $klarna->addArticle (1, utf8_decode ($item->order_item_sku), $name, $discount, (double)$discount_tax_percent, $item_discount_percent, $includeVat); } } // this is not correct yet /* foreach($order['calc_rules'] as $rule){ if ($rule->calc_kind == 'DBTaxRulesBill' or $rule->calc_kind == 'taxRulesBill' or $rule->calc_kind == 'DATaxRulesBill') { $klarna->addArticle (1, "", $rule->calc_rule_name, $rule->calc_amount, 0.0, 0.0, 0); } } */ // Add shipping $shipment = self::convertPrice ($order['details']['BT']->order_shipment + $order['details']['BT']->order_shipment_tax, $order['details']['BT']->order_currency, $cData['currency_code']); foreach ($order['calc_rules'] as $calc_rule) { if ($calc_rule->calc_kind== 'shipment') { $shipment_tax_percent=$calc_rule->calc_value; break; } } $klarna->addArticle (1, "shippingfee", JText::_ ('VMPAYMENT_KLARNA_SHIPMENT'), ((double)(round (($shipment), 2))), round ($shipment_tax_percent, 2), 0, KlarnaFlags::IS_SHIPMENT + KlarnaFlags::INC_VAT); // Add invoice fee if ($klarna_pclass == -1) { //Only for invoices! $payment_without_tax = self::convertPrice ($order['details']['BT']->order_payment, $order['details']['BT']->order_currency, $cData['currency_code']); $payment_with_tax = self::convertPrice ($order['details']['BT']->order_payment + $order['details']['BT']->order_payment_tax, $order['details']['BT']->order_currency, $cData['currency_code']); foreach ($order['calc_rules'] as $calc_rule) { if ( $calc_rule->calc_kind== 'payment') { $payment_tax_percent=$calc_rule->calc_value; break; } } if ($payment_without_tax > 0) { //vmdebug('invoicefee', $payment, $payment_tax); $klarna->addArticle (1, "invoicefee", utf8_decode(JText::_ ('VMPAYMENT_KLARNA_INVOICE_FEE_TITLE')), ((double)(round (($payment_with_tax), 2))), (double)round ($payment_tax_percent, 2), 0, KlarnaFlags::IS_HANDLING + KlarnaFlags::INC_VAT); } } // Add coupon if there is any if (abs ($order['details']['BT']->coupon_discount) > 0.0) { $coupon_discount = self::convertPrice (round ($order['details']['BT']->coupon_discount), $order['details']['BT']->order_currency, $cData['currency_code']); $coupon_discount =(double)(round (abs($coupon_discount), 2)) * -1 ; //vmdebug('discount', $coupon_discount); $klarna->addArticle (1, 'discount',utf8_decode(JText::_ ('VMPAYMENT_KLARNA_DISCOUNT')) . ' ' . utf8_decode($order['details']['BT']->coupon_code), $coupon_discount , 0, 0, KlarnaFlags::INC_VAT); } try { $klarna_shipping = new KlarnaAddr( $order['details']['BT']->email, $shipTo->phone_1, isset($shipTo->phone_2) ? $shipTo->phone_2 : "", utf8_decode ($shipTo->first_name), utf8_decode ($shipTo->last_name), '', utf8_decode ($shipTo->address_1), $shipTo->zip, utf8_decode ($shipTo->city), utf8_decode ($cData['country']), KlarnaHandler::setHouseNo (isset($shipTo->house_no) ? $shipTo->house_no : "", $cData['country_code_3']), KlarnaHandler::setAddress2 ($shipTo->address_2, $cData['country_code_3']) ); } catch (Exception $e) { VmInfo ($e->getMessage ()); return FALSE; } $klarna_reference = ""; // what is that? if ($klarnaData['invoice_type'] == 'company') { $klarna_shipping->isCompany = TRUE; $klarna_shipping->setCompanyName ($shipTo->company); $klarna_comment = $shipTo->first_name . ' ' . $shipTo->last_name; //$klarnaData['reference']; if ($klarna_shipping->getLastName () == "") { $klarna_shipping->setLastName ("-"); } if ($klarna_shipping->getFirstName () == "") { $klarna_shipping->setFirstName ("-"); } } else { $klarna_reference = ""; $klarna_comment = ""; } // Only allow billing and shipping to be the same for Germany and the Netherlands if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) { $klarna_billing = $klarna_shipping; } else { $klarna_billing = self::getBilling ($cData, $order); } $klarna_flags = KlarnaFlags::RETURN_OCR; // get ocr back from KO. $klarna->setComment ($klarna_comment); $klarna->setReference ($klarna_reference, ""); $pno = self::getPNOfromSession ($sessionKlarnaData->KLARNA_DATA, $country); try { $klarna->setAddress (KlarnaFlags::IS_SHIPPING, $klarna_shipping); $klarna->setAddress (KlarnaFlags::IS_BILLING, $klarna_billing); if (isset($klarnaData['year_salary'])) { $klarna->setIncomeInfo ("'yearly_salary'", $klarnaData['year_salary']); } $result = $klarna->addTransaction ($pno, ($klarna->getCountry () == KlarnaCountry::DE || $klarna->getCountry () == KlarnaCountry::NL) ? $klarnaData['gender'] : NULL, $klarna_flags, $klarna_pclass); $result['eid'] = $cData['eid']; $result['status_code'] = $result[2]; $result['status_text'] = JText::_ ('VMPAYMENT_KLARNA_ORDER_STATUS_TEXT_' . $result[2]); return $result; //return $result; } catch (Exception $e) { $result['status_code'] = KlarnaFlags::DENIED; $result['status_text'] = mb_convert_encoding ($e->getMessage (), 'UTF-8', 'ISO-8859-1'). " (#" . $e->getCode () . ")"; return $result; //return $result; //self::redirectPaymentMethod('error', htmlentities($e->getMessage()) . " (#" . $e->getCode() . ")"); } } private static function setAddress2 ($address2, $country) { if ($country == 'NLD') { return $address2; } else { return NULL; } } private static function setHouseNo ($houseNo, $country) { if (($country == 'DEU') or ($country == 'NLD')) { return $houseNo; } else { return NULL; } } /** * Returns a collection of addresses that are connected to the * supplied SSN * * @param $pno The SSN of the user. This method is only available * for swedish customers * @return array */ public static function getAddresses ($pno, $settings, $method) { // Only available for sweden. $addresses = array(); $klarna = new Klarna_virtuemart(); $mode = KlarnaHandler::getKlarnaMode ($method, $settings['country_code_3']); $klarna->config ($settings['eid'], $settings['secret'], KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), $mode); try { $addresses = $klarna->getAddresses ($pno, NULL, KlarnaFlags::GA_GIVEN); } catch (Exception $e) { // the message is returned NOT in UTF-8 $msg = mb_convert_encoding ($e->getMessage (), 'UTF-8', 'ISO-8859-1'); VmInfo ($msg); } unset($klarna); return $addresses; } /** * @static * @param $method * @return array */ public static function fetchAllPClasses ($method) { $message = ''; $success = ''; $results = array(); $countries = self::getKlarnaCountries (); $pc_type = KlarnaHandler::getKlarna_pc_type (); if (empty($pc_type)) { return FALSE; } else { // delete the file directly if (file_exists ($pc_type)) { unlink ($pc_type); } } foreach ($countries as $country) { $active_country = "klarna_active_" . $country; if ($method->$active_country) { // country is CODE 3==> converting to 2 letter country //$country = self::convertCountryCode($method, $country); $lang = self::getLanguageForCountry ($method, $country); $flagImg = JURI::root (TRUE) . '/administrator/components/com_virtuemart/assets/images/flag/' . strtolower ($lang) . '.png'; $flag = ""; try { $settings = self::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, $pc_type, TRUE); $klarna->fetchPClasses ($country); $success .= shopFunctions::getCountryByID ($settings['virtuemart_country_id']); } catch (Exception $e) { $message .= $flag . " " . shopFunctions::getCountryByID ($settings['virtuemart_country_id']) . ": " . $e->getMessage () . ' Error Code #' . $e->getCode () . '
    '; } } } $results['msg'] = $message; $results['notice'] = $success; return $results; //echo $notice; } static function createKlarnaFolder () { $safePath = VmConfig::get ('forSale_path', ''); if ($safePath) { $exists = JFolder::exists ($safePath . 'klarna'); if (!$exists) { $created = JFolder::create ($safePath . 'klarna'); if ($created) { return TRUE; } } else { return TRUE; } } $uri = JFactory::getURI (); $link = $uri->root () . 'administrator/index.php?option=com_virtuemart&view=config'; VmError (JText::sprintf ('VMPAYMENT_KLARNA_CANNOT_STORE_CONFIG', '' . $link . '', JText::_ ('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH'))); return FALSE; } /** * Redirects user to payment method stage. * * @param $type e.g. 'error', ... * @param $message */ public static function redirectPaymentMethod ($type = NULL, $message = NULL) { $log = utf8_encode ($message); //Display the error. if (strlen ($log) > 0) { if ($type === NULL) { $type = 'message'; } $app = JFactory::getApplication (); $app->enqueueMessage (JText::_ (urldecode ($log)), $type); } //Redirect to previous page. $session = JFactory::getSession (); $sessionKlarna = new stdClass(); $sessionKlarna->klarna_error = addslashes ($message); $session->set ('Klarna', serialize ($sessionKlarna), 'vm'); if (isset($_SESSION['klarna_paymentmethod'])) { $pid = $_SESSION['klarna_paymentmethod']; unset($_SESSION['klarna_paymentmethod']); } //$_SESSION['klarna_error'] = addslashes($message); $app = JFactory::getApplication (); $app->enqueueMessage ($message); $app->redirect (JRoute::_ ('index.php?option=com_virtuemart&view=cart',FALSE), JText::_ ('COM_VIRTUEMART_CART_ORDERDONE_DATA_NOT_VALID')); } /** * * @param $address * @return */ public static function splitAddress ($address) { $numbers = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); $characters = array( '-', '/', ' ', '#', '.', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); $specialchars = array('-', '/', ' ', '#', '.'); //Where do the numbers start? Allow for leading numbers $numpos = self::strpos_arr ($address, $numbers, 2); //Get the streetname by splitting off the from the start of the numbers $streetname = substr ($address, 0, $numpos); //Strip off spaces at the end $streetname = trim ($streetname); //Get the housenumber+extension $numberpart = substr ($address, $numpos); //and strip off spaces $numberpart = trim ($numberpart); //Get the start position of the extension $extpos = self::strpos_arr ($numberpart, $characters, 0); //See if there is one, if so if ($extpos != '') { //get the housenumber $housenumber = substr ($numberpart, 0, $extpos); // and the extension $houseextension = substr ($numberpart, $extpos); // and strip special characters from it $houseextension = str_replace ($specialchars, '', $houseextension); } else { //Otherwise, we already have the housenumber $housenumber = $numberpart; } return array($streetname, $housenumber, $houseextension); } /** * * @param $haystack * @param $needle * @param $where * @return */ private static function strpos_arr ($haystack, $needle, $where) { $defpos = 10000; if (!is_array ($needle)) { $needle = array($needle); } foreach ($needle as $what) { if (($pos = strpos ($haystack, $what, $where)) !== FALSE) { if ($pos < $defpos) { $defpos = $pos; } } } return $defpos; } /** * gets Eid and Secret for activated countries. */ public static function getEidSecretArray ($method) { $eid_array = array(); if (isset($method->klarna_merchantid_swe) && $method->klarna_merchantid_swe != "" && $method->klarna_sharedsecret_swe != "") { $eid_array['swe']['secret'] = $method->klarna_sharedsecret_swe; $eid_array['swe']['eid'] = (int)$method->klarna_merchantid_swe; } if (isset($method->klarna_merchantid_nor) && $method->klarna_merchantid_nor != "" && $method->klarna_sharedsecret_nor != "") { $eid_array['nor']['secret'] = $method->klarna_sharedsecret_nor; $eid_array['nor']['eid'] = $method->klarna_merchantid_nor; } if (isset($method->klarna_merchantid_deu) && $method->klarna_merchantid_deu != "" && $method->klarna_sharedsecret_deu != "") { $eid_array['deu']['secret'] = $method->klarna_sharedsecret_deu; $eid_array['deu']['eid'] = $method->klarna_merchantid_deu; } if (isset($method->klarna_nld_merchantid) && $method->klarna_nld_merchantid != "" && $method->klarna_sharedsecret_nld != "") { $eid_array['nld']['secret'] = $method->klarna_sharedsecret_nld; $eid_array['nld']['eid'] = $method->klarna_nld_merchantid; } if (isset($method->klarna_merchantid_dnk) && $method->klarna_merchantid_dnk != "" && $method->klarna_sharedsecret_dnk != "") { $eid_array['dnk']['secret'] = $method->klarna_sharedsecret_dnk; $eid_array['dnk']['eid'] = $method->klarna_merchantid_dnk; } if (isset($method->klarna_merchantid_fin) && $method->klarna_merchantid_fin != "" && $method->klarna_sharedsecret_fin != "") { $eid_array['fin']['secret'] = $method->klarna_sharedsecret_fin; $eid_array['fin']['eid'] = $method->klarna_merchantid_fin; } return $eid_array; } /** * @param $obj * @param int $level * @return array */ public function xmlToArray ($obj, $level = 0) { $aResult = array(); if (!is_object ($obj)) { return $aResult; } $aChild = (array)$obj; if (sizeof ($aChild) > 1) { foreach ($aChild as $sName => $mValue) { if ($sName == "@attributes") { $sName = "_attributes"; } if (is_array ($mValue)) { foreach ($mValue as $ee => $ff) { if (!is_object ($ff)) { $aResult[$sName][$ee] = $ff; } else { if (get_class ($ff) == 'SimpleXMLElement') { $aResult[$sName][$ee] = self::xmlToArray ($ff, $level + 1); } } } } else { if (!is_object ($mValue)) { $aResult[$sName] = $mValue; } else { if (get_class ($mValue) == 'SimpleXMLElement') { $aResult[$sName] = self::xmlToArray ($mValue, $level + 1); } } } } } else { if (sizeof ($aChild) > 0) { foreach ($aChild as $sName => $mValue) { if ($sName == "@attributes") { $sName = "_attributes"; } if (!is_array ($mValue) && !is_object ($mValue)) { $aResult[$sName] = $mValue; } else { if (is_object ($mValue)) { $aResult[$sName] = self::xmlToArray ($mValue, $level + 1); } else { foreach ($mValue as $sNameTwo => $sValueTwo) { if (!is_object ($sValueTwo)) { $aResult[$obj->getName ()][$sNameTwo] = $sValueTwo; } else { if (get_class ($sValueTwo) == 'SimpleXMLElement') { $aResult[$obj->getName ()][$sNameTwo] = self::xmlToArray ($sValueTwo, $level + 1); } } } } } } } } return $aResult; } /** * @static * @param $settings * @param $mode * @param $klarna_invoice_no * @return string */ public static function checkOrderStatus ($settings, $mode, $orderNumber) { try { $klarna = new Klarna_virtuemart(); $klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE); vmdebug ('checkOrderStatus', $klarna); $os = $klarna->checkOrderStatus ($orderNumber, 1); } catch (Exception $e) { $msg = $e->getMessage () . ' #' . $e->getCode () . '
    '; VmError ($msg); return $msg; } //$os = self::getStatusForCode($os); return $os; } /** * Return pclasses stored in json file. */ public static function getPClasses ($type = NULL, $mode, $settings) { //$settings = self::countryData($method, $country); try { $klarna = new Klarna_virtuemart(); $klarna->config ($settings['eid'], $settings['secret'], $settings['country'], $settings['language'], $settings['currency'], $mode, VMKLARNA_PC_TYPE, KlarnaHandler::getKlarna_pc_type (), TRUE); return $klarna->getPClasses ($type); } catch (Exception $e) { } } static function getCheapestPclass ($kCheckout, &$cheapest, &$minimum) { $pclasses = $kCheckout->aPClasses; if (empty($pclasses)) { $minimum = 0; return; } $cheapest = 0; $minimum = ''; foreach ($pclasses as $pclass) { if ($cheapest == 0 || $pclass['monthlyCost'] < $cheapest) { $cheapest = $pclass['monthlyCost']; } if ($pclass['pclass']->getMinAmount () < $minimum || $minimum === '') { $minimum = $pclass['pclass']->getMinAmount (); } } } /** * @param string $fld * @return string */ public static function getVendorCountry ($fld = 'country_3_code') { if (!class_exists ('VirtueMartModelVendor')) { JLoader::import ('vendor', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'models'); } $virtuemart_vendor_id = 1; $model = VmModel::getModel ('vendor'); $vendorAddress = $model->getVendorAdressBT ($virtuemart_vendor_id); $vendor_country = ShopFunctions::getCountryByID ($vendorAddress->virtuemart_country_id, $fld); return $vendor_country; } /** * @param $klarnaError * @param $klarnaOption * @return bool */ function getKlarnaError (&$klarnaError, &$klarnaOption) { $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if (empty($sessionKlarna)) { return FALSE; } $sessionKlarnaData = unserialize ($sessionKlarna); if (isset($sessionKlarnaData->klarna_error) and isset($sessionKlarnaData->klarna_paymentmethod)) { $klarnaError = $sessionKlarnaData->klarna_error; // it is a message to display $klarnaOption = $sessionKlarnaData->klarna_paymentmethod; return TRUE; } else { return FALSE; } return FALSE; } function setKlarnaErrorInSession ($msg, $option) { $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if (empty($sessionKlarna)) { $sessionKlarnaData = new stdClass(); } else { $sessionKlarnaData = unserialize ($sessionKlarna); } $sessionKlarnaData->klarna_error = $msg; //$sessionKlarnaData->klarna_option = $option; $session->set ('Klarna', serialize ($sessionKlarnaData), 'vm'); } /** * */ function clearKlarnaError () { $session = JFactory::getSession (); $sessionKlarna = $session->get ('Klarna', 0, 'vm'); if ($sessionKlarna) { $sessionKlarnaData = unserialize ($sessionKlarna); if (isset($sessionKlarnaData->klarna_error)) { unset($sessionKlarnaData->klarna_error); //unset($sessionKlarnaData->klarna_option); $session->set ('Klarna', serialize ($sessionKlarnaData), 'vm'); } } } /** * @static * @param $method * @return int */ static function getKlarnaMode ($method, $country) { //return Klarna::BETA; // It is the VM specific store ID to test $merchant_id = strtolower ('klarna_merchantid_' . $country); if ($method->$merchant_id == VMPAYMENT_KLARNA_MERCHANT_ID_VM or $method->$merchant_id == VMPAYMENT_KLARNACHECKOUT_MERCHANT_ID_VM or $method->$merchant_id == VMPAYMENT_KLARNA_MERCHANT_ID_DEMO) { return Klarna::BETA; } else { return Klarna::LIVE; } } /** * @static * @param $mode * @return bool */ static function getKlarnaSSL ($mode) { return ($mode == Klarna::LIVE); } /** * @static * @param $price * @param string $toCurrency * @return float */ static function convertPrice ($price, $fromCurrency, $toCurrency = '', $cartPricesCurrency = '') { if (!(is_int ($toCurrency) or is_numeric ($toCurrency)) && !empty($toCurrency)) { $toCurrency = ShopFunctions::getCurrencyIDByName ($toCurrency); } if ($fromCurrency == $toCurrency) { return $price; } // product prices or total in cart is always in vendor currency $priceInNewCurrency = vmPSPlugin::getAmountInCurrency($price,$toCurrency); // set back the currency display if (empty($cartPricesCurrency)) { $cartPricesCurrency = $fromCurrency; } $cd = CurrencyDisplay::getInstance ($cartPricesCurrency); vmDebug ('convertPrice', $price, $toCurrency, $fromCurrency, $cartPricesCurrency,$priceInNewCurrency); return $priceInNewCurrency['value']; } /* * if client has not given address then get cdata depending on the currency * otherwise get info depending on the country */ /** * @static * @param $method * @param $address * @return array|null */ static function getcData ($method, $address) { if (!isset($address['virtuemart_country_id'])) { $vendor_country = KlarnaHandler::getVendorCountry (); $cData = self::countryData ($method, $vendor_country); } else { $cart_country_code_3 = ShopFunctions::getCountryByID ($address['virtuemart_country_id'], 'country_3_code'); // the user gave an address, get info according to his country $cData = self::countryData ($method, $cart_country_code_3); } return $cData; } /** * @static * @return null|string */ static function getKlarna_pc_type () { $safePath = VmConfig::get ('forSale_path', ''); if ($safePath) { return $safePath . "klarna/klarna.json"; } else { $uri = JFactory::getURI (); $link = $uri->root () . 'administrator/index.php?option=com_virtuemart&view=config'; VmError (JText::sprintf ('VMPAYMENT_KLARNA_CANNOT_STORE_CONFIG', '' . $link . '', JText::_ ('COM_VIRTUEMART_ADMIN_CFG_MEDIA_FORSALE_PATH'))); return NULL; } } /** * Sweden: yymmdd-nnnn, it can be sent with or without dash "-" or with or without the two first numbers in the year. * Finland: ddmmyy-nnnn * Denmark: ddmmyynnnn * Norway: ddmmyynnnnn * Germany: ddmmyyyy * Netherlands: ddmmyyyy * * @static * @param $billTo * @param $country * @return string */ static function getPNOfromSession ($sessionData, $country) { if (($country == "NLD" || $country == "DEU")) { $pno = $sessionData['pno_frombirthday']; } else { $pno = $sessionData['socialNumber']; } return $pno; } /** * @param $data * @return bool */ static function checkDataFromEditPayment ($data, $country3) { if (!class_exists ('VirtueMartModelUserfields')) { require(JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'userfields.php'); } $errors = array(); /* if ($country3 == "DEU") { $consent = JRequest::getVar ('klarna_consent'); if ($consent != 'on') { $errors = JText::_ ('VMPAYMENT_KLARNA_NO_CONSENT'); } } // todo later $userFieldsModel = VmModel::getModel ('userfields'); $userFields = $userFieldsModel->getUserFields ( 'account' , array('required' => FALSE, 'delimiters' => TRUE, 'captcha' => TRUE, 'system' => FALSE) , array('delimiter_userinfo', 'name', 'username', 'password', 'password2', 'address_type_name', 'address_type', 'user_is_vendor', 'agreed')); $required_shopperfields_vm = Klarnahandler::getKlarnaVMGenericShopperFields (FALSE); $required_shopperfields_bycountry = KlarnaHandler::getKlarnaSpecificShopperFields (); $required_shopperfields = array_merge ($required_shopperfields_vm, $required_shopperfields_bycountry[$country3]); foreach ($userFields as $userField) { if (in_array ($userField->name, $required_shopperfields)) { if (empty($data[$userField->name])) { $errors[] = JText::_($userField->title); } } } */ // Quick and durty .. but it works $kIndex = "klarna_"; if ($country3 == "SWE") { if (JRequest::getVar ('klarna_invoice_type') == 'company') { if (strlen (trim ((string)JRequest::getVar ('klarna_company_name'))) == 0) { $errors[] = 'VMPAYMENT_KLARNA_COMPANY_NAME'; } } else { if (!KlarnaEncoding::checkPNO ($data['socialNumber'], KlarnaEncoding::PNO_SE)) { $errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER'; } } } else { if ($data['phone'] == '') { $errors[] = 'VMPAYMENT_KLARNA_PHONE_NUMBER'; } if ($data['street'] == '') { $errors[] = 'VMPAYMENT_KLARNA_STREET_ADRESS'; } if ($data['first_name'] == '') { $errors[] = 'VMPAYMENT_KLARNA_FIRST_NAME'; } if ($data['last_name'] == '') { $errors[] = 'VMPAYMENT_KLARNA_LAST_NAME'; } if ($data['city'] == '') { $errors[] = 'VMPAYMENT_KLARNA_ADDRESS_CITY'; } if ($data['zip'] == '') { $errors[] = 'VMPAYMENT_KLARNA_ADDRESS_ZIP'; } } // German and dutch if ($country3 == "NLD" || $country3 == "DEU") { if ($data['street'] == '') { $errors[] = 'VMPAYMENT_KLARNA_STREET_ADRESS'; } if ($data['house_no'] == '') { $errors[] = 'VMPAYMENT_KLARNA_ADDRESS_HOMENUMBER'; } if ($country3 == "DEU") { if ($data['consent'] != 'on') { $errors[] = 'VMPAYMENT_KLARNA_NO_CONSENT'; } } if ($data['pno_frombirthday'] == '') { $errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER'; } if ($data['gender'] == '') { $errors[] = 'VMPAYMENT_KLARNA_SEX'; } } // General /* the email is not in the payment form if ($data['emailAddress'] == '') { $errors[] = 'VMPAYMENT_KLARNA_EMAIL'; } */ // Norwegian, Danish and Finnish if (($country3 == "NOR") || ($country3 == "DNK") || $country3 == "FIN") { if ($data['socialNumber'] == '') { $errors[] = 'VMPAYMENT_KLARNA_PERSONALORORGANISATIO_NUMBER'; } } if (!empty($errors)) { $msg = JText::_ ('VMPAYMENT_KLARNA_ERROR_TITLE_2'); foreach ($errors as $error) { $msg .= "
  • " . JText::_ ($error) . "
  • "; } $option=NULL; self::setKlarnaErrorInSession ($msg, $option); return $msg; } return NULL; } /** * @static * @return array */ static function getKlarnaSpecificShopperFields () { return array( "SWE" => array( "email"), "DNK" => array(), // should not be given to the shopper year_salary "NOR" => array(), "FIN" => array(), "NLD" => array( "address_2", "house_no"), "DEU" => array( "house_no") ); } /** * @return array */ static function getKlarnaVMGenericShopperFields ($all = TRUE) { $required = array("first_name", "last_name", "address_1", "city", "zip", "phone_1", "virtuemart_country_id"); if ($all) { $required = array_merge ($required, array("company")); } return $required; } static function getKlarnaShopperFieldsType () { return array("socialNumber"=> "text", "email" => "email", "birthday" => "date", "address_2" => "text", "house_no" => "text", ); } /** * */ function getByFieds () { $required_shopperfields_byfields = array( "socialNumber" => array("SWE", "DNK", "NOR", "FIN"), "year_salary" => array("DNK"), "address_2", "birthday" => array("DEU", "NLD"), "house_no" => array("NLD"), "email" => array("SWE") ); } /** * Get the shipToAddress which might differ from default address. * From VM shopperFields to Klarna Fields */ public static function getShipToAddress ($cart) { //vmdebug('getShipToAddress',$cart); if (VMKLARNA_SHIPTO_SAME_AS_BILLTO) { $shipTo = $cart->BT; } else { $shipTo = (($cart->ST == 0 or empty($cart->ST)) ? $cart->BT : $cart->ST); } return self::getKlarnaFieldsFromVmShopperFields ($shipTo, $cart->BT['email']); } /** * @static * @param $from * @param $from_email * @return array */ static function getKlarnaFieldsFromVmShopperFields ($from, $from_email) { $klarnaFields = array(); switch ($from['title']) { case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MR'): $klarnaFields['gender'] = KlarnaFlags::MALE; break; case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MISS'): case JText::_ ('COM_VIRTUEMART_SHOPPER_TITLE_MRS'): $klarnaFields['gender'] = KlarnaFlags::FEMALE; break; default: $klarnaFields['gender'] = NULL; break; } $country_code_3 = ShopFunctions::getCountryByID ($from['virtuemart_country_id'], 'country_3_code'); $klarnaFields['email'] = $from_email; $klarnaFields['country'] = @ShopFunctions::getCountryByID (@$from['virtuemart_country_id'], 'country_3_code'); $klarnaFields['socialNumber'] = @$from['socialNumber']; $klarnaFields['houseNr'] = @$from['house_no']; $klarnaFields['houseExt'] = @$from['address_2']; $klarnaFields['first_name'] = @$from['first_name']; if ($country_code_3 == 'NLD') { $klarnaFields['last_name'] = @$from['middle_name'] . " " . @$from['last_name']; } else { $klarnaFields['last_name'] = @$from['last_name']; } $klarnaFields['reference'] = $from['first_name'] . ' ' . $from['last_name']; $klarnaFields['company_name'] = @$from['company_name']; $klarnaFields['phone'] = @$from['phone_1']; $klarnaFields['street'] = @$from['address_1']; $klarnaFields['city'] = @$from['city']; $klarnaFields['country'] = $country_code_3; $klarnaFields['state'] = @$from['state']; $klarnaFields['zip'] = @$from['zip']; $klarnaFields['birthday'] = @$from['birthday']; if (isset($from['birthday']) and !empty($from['birthday'])) { $date = explode ("-", $from['birthday']); if (is_array ($date)) { $klarnaFields['birth_year'] = $date['0']; $klarnaFields['birth_month'] = $date['1']; $klarnaFields['birth_day'] = $date['2']; } } return $klarnaFields; } function checkNLpriceCondition ($price) { // Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros. if ($price > 250) { // 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; } return TRUE; } function checkPartNLpriceCondition ($cart) { // Since 12/09/12: merchants can sell goods with Klarna Invoice up to thousands of euros. // convert price in euro //$euro_currency_id = ShopFunctions::getCurrencyByName( 'EUR'); $price = KlarnaHandler::convertPrice ($cart->pricesUnformatted['billTotal'], $cart->pricesCurrency, 'EUR',$cart->pricesCurrency); return self::checkNLpriceCondition ($price); } } klarna/klarna/helpers/klarna.cfg000066600000000177151372777310012705 0ustar00 klarna/klarna/assets/js/klarna_invoice.js000066600000000134151372777310014543 0ustar00// Load when document finished loading jQuery( function (){ klarna.invoiceReady(); }); klarna/klarna/assets/js/klarna_admin.js000066600000011040151372777310014175 0ustar00jQuery(function($){ setTimeout('showCountries()', 10); flagListener(); //setTimeout('setExtraInfo()', 10); setTimeout('showPclasses()', 10); $(".update_pclasses a").click( function(e){ e.preventDefault(); form = $(this).parents("form") ; var link = $(this).attr("href"); var datas = $(this).parents("form").serializeArray(); datas.push({"name":"redirect","value":"no"}); datas.push({"name":"task","value":"save"}); $.post(link,datas,function(data) { if (data = "ok") { console.log("update table"); datas.push({"name":"view","value":"plugin"}); datas.push({"name":"name","value":"klarna"}); datas.push({"name":"task","value":"plugin"}); $.getJSON(link , datas,function(update) { // update json array msg,notice,pclasses $('#PClassesSuccessResult').hide().html(update.msg+'
    '+update.notice).slideToggle(1000).delay(2000).slideToggle(500); //console.log("update pclasse"); $('#pclasses').html(update.pclasses); }); } }); return false; }); }); function showCountries() { jQuery('select[name=KLARNA_SELECTED_COUNTRIES[]] option:selected').each(function() { var value = jQuery(this).attr('value'); var code = convert(value); var field = 'fieldset#'+code+'_settings'; jQuery(field).removeClass('hide'); jQuery('img#'+code).removeClass('inactive'); }); } // The ExtraInfo box in the backend empties itself every time you enter the // backend if it contains php code, this function puts it back. function setExtraInfo() { var einfo = "<"+"?php include(JPATH_SITE . '/components/com_klarna/extrainfo.php'); "+"?"+">"; var current = jQuery('textarea').attr('name', 'payment_extrainfo').text(); if (current.search('JPATH_SITE') <0 ) { jQuery('textarea').attr('name','payment_extrainfo').text(einfo+current); } } function showPclasses() { jQuery('#pclass_field').click(function(){ var pclass_field=jQuery(this); jQuery('#pclasses').slideToggle("fast", function() { if (pclass_field.find('span').hasClass('expand_arrow')) pclass_field.find('span').addClass('collapse_arrow').removeClass('expand_arrow') else pclass_field.find('span').addClass('expand_arrow').removeClass('collapse_arrow') // jQuery(this).parent().find('#arrow').html(''); }); }); } function convert(country) { switch(country) { case "SWE": return "SE"; case "NOR": return "NO"; case "DNK": return "DK"; case "FIN": return "FI"; case "NLD": return "NL"; case "DEU": return "DE"; default: return null; // not supported by Klarna yet } } function convert_twoletter(country) { switch(country) { case "SE": return "SWE"; case "NO": return "NOR"; case "DK": return "DNK"; case "FI": return "FIN"; case "NL": return "NLD"; case "DE": return "DEU"; default: return null; // not supported by Klarna yet } } function flagListener() { jQuery('#klarna_countries').find('span').click(function() { var code = jQuery(this).attr('id'); toggleActive(code); }); } function toggleActive(code) { var field = 'fieldset#'+code+'_settings'; var tlc = convert_twoletter(code); if (jQuery(field).is(':hidden')) { jQuery(field).removeClass('hide'); jQuery('img#'+code).removeClass('inactive').addClass('active'); jQuery('span#'+code).removeClass('inactive').addClass('active'); jQuery('#KLARNA_SELECTED_COUNTRIES > option[value='+tlc+']').attr('selected', 'selected'); } else if (jQuery(field).is(':visible')) { jQuery(field).addClass('hide'); jQuery('img#'+code).addClass('inactive').removeClass('active'); jQuery('span#'+code).addClass('inactive').removeClass('active'); jQuery('#KLARNA_SELECTED_COUNTRIES > option[value='+tlc+']').removeAttr('selected'); } } klarna/klarna/assets/js/klarna_general.js000066600000065707151372777310014545 0ustar00 var klarna_js_loaded = true; if (typeof klarna == "undefined") { var $$ = $; var $ = jQuery; var klarna = { invoice_fee: 0, sum : 0, gender : '', klarnaGeneralLoaded : true, different_language : false, currentMinHeight_part : 0, currentMinHeight_spec : 0, currentMinHeight_invoice : 0, red_baloon_busy : false, blue_baloon_busy : false, address_busy : false, baloons_moved : false, changeLanguage_busy : false, showing_companyNotAlowed_box : false, gChoice : '', stype : '', errorHandler: { show: function(parentBox, message, code, type) { var errorHTML = '
    '+message+'
    '; errorHTML += '
    '; if ( type != '' ) { errorHTML += ''+type+''; } if ( code != '' ) { errorHTML += '#'+code+'
    '; } if (jQuery('#klarna_red_baloon').length == 0) { klarna.errorHandler.create(parentBox); } jQuery('#klarna_red_baloon_content').html(errorHTML); if (typeof showRedBaloon != 'undefined') showRedBaloon(parentBox); }, /** * Creates the red baloon used to show error messages */ create: function(parentBox) { jQuery( '
    ' + '
    ' + '
    ' + '
    ' + '
    ').appendTo(parentBox); }, prepareRedBaloon: function () { if ((typeof klarna.global.red_baloon_content != 'undefined') && (klarna.global.red_baloon_content != '') ) { var box; if (klarna.global.red_baloon_box != '') { box = jQuery('#' + klarna.global.red_baloon_box) } this.show(box, klarna.global.red_baloon_content); } }, showRedBaloon: function (box) { if (this.busy) return; this.busy = true; var field; if (typeof box == 'undefined') { if (gChoice == klarna.global.invoice_name) { box = jQuery(document).find('#klarna_box_invoice'); } else if (gChoice == klarna.global.part_name) { box = jQuery(document).find('#klarna_box_part'); } else if (gChoice == klarna.global_spec_name) { box = jQuery(document).find('#klarna_box_spec'); } } if (typeof box != 'undefined') { field = box.find('.klarna_logo'); } if (typeof field == 'undefined' || field.length == 0) { field = jQuery('.klarna_logo:visible'); } if (field.length > 0) { var callback = this.fadeRedBaloon; var position = field.offset(); var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6); if (top < 0) top = 10; position.top = top; var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2); position.left = left; jQuery('#klarna_red_baloon').css(position); jQuery('#klarna_red_baloon').fadeIn('slow', function () { setTimeout(callback, 3000); }); } else { this.busy = false; } }, fadeRedBaloon: function () { this.busy = false; jQuery('#klarna_red_baloon').addClass('klarna_fading_baloon'); }, hideRedBaloon: function () { this.busy = false; this.showing_address_error = false; jQuery('#klarna_red_baloon').remove(); } }, hidePaymentOption : function (box, animate) { if (typeof animate == 'undefined') { animate = false; } if (animate) { jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom'). hide(); } else { jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom'). fadeOut('fast'); } jQuery(box).animate({'min-height': '55px'}, 200); klarna.showHideIlt(jQuery(box).find('.klarna_box_ilt'), false, animate); }, showPaymentOption : function (box, animate, currentMinHeight, different_language) { if (typeof animate == 'undefined') { animate = false; } if (animate) { jQuery(box).animate({"min-height": currentMinHeight}, 200, function () { klarna.showHideIlt(jQuery(this).find('.klarna_box_ilt'), true); jQuery(this).find('.klarna_box_bottom').fadeIn('fast', function () { jQuery('.klarna_box_bottom_content_loader').fadeOut(); if (klarna.showing_companyNotAlowed_box) { klarna.hideRedBaloon(); } }); jQuery(this).find('.klarna_box_top_right').fadeIn('fast'); if (different_language) { jQuery(this).find('.klarna_box_bottom_languageInfo').fadeIn('fast'); jQuery('.klarna_box_bottom_languageInfo').fadeIn('fast'); } }); } else { jQuery(box).find('.klarna_box_top_right, .klarna_box_bottom').show('fast'); klarna.showHideIlt(jQuery(box).find('.klarna_box_ilt'), true, animate); } }, initPaymentSelection : function (choice) { var isklarna = choice.hasClass('klarnaPayment'); klarna.gChoice = ''; klarna.stype = choice.data("stype"); if ( isklarna ) klarna.gChoice = choice.attr('id'); //jQuery('input[value="'+choice+'"]').attr("id"); var klarnaBox = jQuery('#paymentForm .klarnaPayment'); klarnaBox.each(function () { var thisStype = jQuery(this).data("stype"); if (klarna.stype != thisStype) klarna.hidePaymentOption('#klarna_box_'+thisStype); else klarna.choosePaymentOption(klarna.stype); }); }, choosePaymentOption : function (choice) { klarna.hideRedBaloon(); klarna.hideBlueBaloon(); klarna.showPaymentOption(jQuery('#klarna_box_'+choice), true, klarna['currentMinHeight_'+klarna.stype], klarna.different_language); }, setGender : function (context, gender) { // This should be refactored to not be able to set other non-gender radio buttons var value; if (gender == 'f' || gender == '0') { jQuery('.Klarna_radio[value=0]', context).attr('checked', 'checked'); } else //if (gender == 'm' || gender == '1') { jQuery('.Klarna_radio[value=1]', context).attr('checked', 'checked'); } }, /** * Hook up jQuery callbacks for the given klarna_box_container(s) or * all klarna options in the document */ initPaymentOptions : function (opts) { if (typeof opts == 'undefined') { opts = jQuery(document); } // specialCampaign only if(typeof InitKlarnaSpecialPaymentElements != 'undefined') InitKlarnaSpecialPaymentElements('specialCampaignPopupLink', klarna.eid, klarna.countryCode); // P-Classes box actions jQuery('.klarna_box', opts).find('ol').find('li').mouseover(function (){ jQuery(this).not('.klarna_box_click').addClass('klarna_box_over'); }).mouseout(function (){ jQuery(this).not('.klarna_box_click').removeClass('klarna_box_over') }).click(function (){ // Reset list and move chosen icon to newly selected pclass chosen = jQuery(this).parent("ol").find('img') klarna.resetListBox(jQuery(this).parent("ol")); chosen.appendTo(jQuery(this).find('div')); jQuery(this).attr("class", "klarna_box_click"); // Update input field with pclass id var value = jQuery(this).find('span').html(); var name = jQuery(this).parent("ol").attr("id"); jQuery(this).closest('.klarna_box').find("input.paymentPlan").attr("value", value); }); if (klarna.countryCode == "de" || klarna.countryCode == "nl") { klarna.setGender(opts, klarna.gender); } // Input field on focus jQuery('.klarna_box', opts).find('input').focusin(function () { klarna.setBaloonInPosition(jQuery(this), false); }).focusout(function () { klarna.hideBaloon(); }); jQuery('.klarna_box_top_flag_list img', opts).click(function (){ if (klarna.changeLanguage_busy == false) { klarna.changeLanguage_busy = true; var newIso = jQuery(this).attr("alt"); jQuery('.box_active_language', opts).attr("src", jQuery(this).attr("src")); var box = jQuery(this).parents('.klarna_box_container'); var params; var values; var boxType = box.find('.klarna_box').attr("id"); var Type = boxType.substring( 11 );//'klarna_box_' if (!Type) { console.log(boxType); return ; } klarna.changeLanguage(box, klarna.params, newIso, klarna.countryCode, Type); } }); setTimeout('klarna.prepareRedBaloon()', 1000); jQuery('.klarna_box_bottom_languageInfo', opts).mousemove(function (e) { klarna.showBlueBaloon(e.pageX, e.pageY, jQuery(this).find('img').attr("alt")); }); jQuery('.klarna_box_bottom_languageInfo', opts).mouseout(function () { klarna.hideBlueBaloon(); }); jQuery('input.gender.Klarna_radio', opts).bind('change', function () { klarna.gender = jQuery(this).val(); }); jQuery('.Klarna_pnoInputField', opts).each(function (){ var pnoField = jQuery(this); jQuery(this).bind("keyup change blur focus", function (){ klarna.pnoUpdated(jQuery(this), (jQuery(this).parents('.klarna_box').attr("id") == "klarna_box_invoice")); }); }); }, doDocumentIsReady : function (klarnaBox) { klarnaBox.each(function () { var type = jQuery(this).parents('table').find('.klarnaPayment').data("stype"); klarna['currentMinHeight_'+type] = jQuery(this).children('.klarna_box_top').height(); }); klarna.initPaymentOptions(); }, pnoUpdated : function (box, companyAllowed) { var pno_value = jQuery.trim(jQuery(box).val()); // Set the PNO to the other fields jQuery('.Klarna_pnoInputField').val(pno_value); // Do check if (pno_value != "") { jQuery('.klarna_box_bottom_content_loader').is(":hidden").fadeIn('fast'); if (!validateSocialSecurity(pno_value)) { jQuery('.klarna_box_bottom_content_loader').fadeOut('fast'); jQuery('.klarna_box_bottom_address').is(":visible").slideUp('fast'); } else { klarna.getAddress (jQuery(box).closest('.klarna_box'), pno_value, companyAllowed); } } else { jQuery('.referenceDiv').is(":visible").slideUp('fast'); // jQuery('.referenceDiv').is(":hidden").css({"display":"none"}); //Ilogic ! jQuery('.klarna_box_bottom_content_loader').fadeOut('fast'); jQuery('.klarna_box_bottom_address').is(":visible").slideUp('fast'); //jQuery('.klarna_box_bottom_address').is(":hidden").css({"display":"none"}); // Ilogic ! } }, /** * Showing and hiding the ILT questions * * @param field * @param show * @param animate */ showHideIlt : function (field, show, animate) { if (show == false) { if (animate == true) field.slideUp('fast'); else field.hide(); } else { var length = field.find('.klarna_box_iltContents').find('.klarna_box_ilt_question').length; if (length > 0) { if (animate == true) field.slideDown('fast'); else field.show(); } } }, prepareRedBaloon: function () { if (klarna.red_baloon_content != '') { if ( typeof code == 'undefined' ) { code = ''; } klarna.errorHandler.show(jQuery('#'+klarna.red_baloon_box), klarna.red_baloon_content, code, ''); } }, showRedBaloon : function (box) { if (klarna.red_baloon_busy) return; klarna.red_baloon_busy = true; var field; if (typeof box == 'undefined') { if (klarna.gChoice == "klarna_invoice") { box = jQuery('#klarna_box_invoice'); } else if (klarna.gChoice == "klarna_partPayment") { box = jQuery('#klarna_box_part'); } else if (klarna.gChoice == "klarna_SpecCamp") { box = jQuery('#klarna_box_spec'); } } if (typeof box != 'undefined') { field = box.find('.klarna_logo'); } if (typeof field == 'undefined' || field.length == 0) { field = jQuery('.klarna_logo:visible'); } var position = field.offset(); var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6); if (top < 0) top = 10; position.top = top; var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2); position.left = left; jQuery('#klarna_red_baloon').css(position); jQuery('#klarna_red_baloon').fadeIn('slow', function () { klarna.red_baloon_busy = false; setTimeout('klarna.fadeRedBaloon()', 3000); }); }, getAddress : function (parentBox, pno_value, companyAllowed) { if (!klarna.address_busy) { klarna.address_busy = true; data = { action: 'getAddress', country: klarna.countryCode, pno: pno_value } // Get the new klarna_box jQuery.ajax({ type: "GET", url: ajax_path, data: data, success: function(xml){ jQuery(xml).find('error').each(function() { var msg = jQuery(this).find('message').text(); var code = jQuery(this).find('code').text(); var type = jQuery(this).find('type').text(); jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () { klarna.address_busy = false; }); klarna.errorHandler.show(parentBox, msg, code, type); }); jQuery(xml).find('getAddress').each(function() { addresses = AddressCollection.fromXML(this); if (typeof klarna.params_invoice != "undefined") addresses.render('#klarna_box_invoice', klarna.params_invoice['shipmentAddressInput']); if (typeof klarna.params_part != "undefined") addresses.render('#klarna_box_part', klarna.params_part['shipmentAddressInput']); if (typeof klarna.params_spec != "undefined") addresses.render('#klarna_box_spec', klarna.params_spec['shipmentAddressInput']); jQuery.each(addresses.addresses, function(i, addr) { if (addr.isCompany) { jQuery('#invoiceType').val("company"); jQuery('.referenceDiv').slideDown('fast'); if (addresses.mode == Address.Single) { jQuery('.klarna_box_bottom').animate({"min-height": "300px"},'fast'); } if (companyAllowed == false && typeof klarna.lang_companyNotAllowed != "") { showRedBaloon(jQuery(box)); jQuery('#klarna_red_baloon_content div').html(klarna.lang_companyNotAllowed); klarna.showing_companyNotAlowed_box = true; } else { klarna.hideRedBaloon(); } } else { jQuery('#invoiceType').val("private"); jQuery('.referenceDiv').slideUp('fast'); jQuery('.klarna_box_bottom').animate({"min-height": "250px"},'fast'); if (klarna.showing_companyNotAlowed_box) klarna.hideRedBaloon(); } }); jQuery('.klarna_box_bottom_address').slideDown('fast'); jQuery('.klarna_box_bottom_content_loader').fadeOut('fast', function () { klarna.address_busy = false; klarna.hideRedBaloon(); }); }); klarna.address_busy = false; } }); } }, showBlueBaloon : function (x, y, text) { jQuery('#klarna_blue_baloon_content div').html(text); var top = (y - jQuery('#klarna_blue_baloon').height())-5; var left = (x - (jQuery('#klarna_blue_baloon').width()/2)+5); jQuery('#klarna_blue_baloon').css({"left": left, "top": top}); jQuery('#klarna_blue_baloon').show(); }, hideBlueBaloon : function () { jQuery('#klarna_blue_baloon').hide(); }, showRedBaloonX : function (box) { if (klarna.red_baloon_busy) return; klarna.red_baloon_busy = true; var field; if (typeof box == 'undefined') { if (klarna.gChoice == "klarna_invoice") { box = jQuery('#klarna_box_invoice'); } else if (klarna.gChoice == "klarna_partPayment") { box = jQuery('#klarna_box_part'); } else if (klarna.gChoice == "klarna_SpecCamp") { box = jQuery('#klarna_box_spec'); } } if (typeof box != 'undefined') { field = box.find('.klarna_logo'); } if (typeof field == 'undefined' || field.length == 0) { field = jQuery('.klarna_logo:visible'); } var position = field.offset(); var top = (position.top - jQuery('#klarna_red_baloon').height()) + (jQuery('#klarna_red_baloon').height() / 6); if (top < 0) top = 10; position.top = top; var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() / 2); position.left = left; jQuery('#klarna_red_baloon').css(position); jQuery('#klarna_red_baloon').fadeIn('slow', function () { klarna.red_baloon_busy = false; setTimeout('klarna.fadeRedBaloon()', 3000); }); }, fadeRedBaloon : function () { if (klarna.red_baloon_busy) return; jQuery('#klarna_red_baloon').addClass('klarna_fading_baloon'); }, hideRedBaloon : function () { if (klarna.red_baloon_busy) return; if (jQuery('#klarna_red_baloon').is(':visible') && !klarna.red_baloon_busy) { jQuery('#klarna_red_baloon').fadeOut('fast', function () { klarna.red_baloon_busy = false; klarna.showing_companyNotAlowed_box = false; }); } }, /** * This function is only available for swedish social security numbers */ validateSocialSecurity : function (vPNO) { if (typeof vPNO == 'undefined') return false; return vPNO.match(/^([1-9]{2})?[0-9]{6}[-\+]?[0-9]{4}$/) }, resetListBox : function (listBox) { listBox.find('li').each(function (){ if (jQuery(this).attr("id") == "click") { jQuery(this).attr("id", ""); } jQuery(this).find('div img').remove(); }); }, hideBaloon : function (callback) { if (jQuery('#klarna_baloon').is(":visible")) { jQuery('#klarna_baloon').fadeOut('fast', function (){ if( callback ) callback(); return true; }); } else { if( callback ) callback(); return true; } }, setBaloonInPosition : function (field, red_baloon) { klarna.hideBaloon(function (){ var position = field.offset(); var name = field.attr('name'); var value = field.attr('alt'); if (!value && !red_baloon) { return false; } if (!red_baloon) { jQuery('#klarna_baloon_content div').html(value); var top = position.top - jQuery('#klarna_baloon').height(); if (top < 0) top = 10; position.top = top; var left = (position.left + field.width()) - (jQuery('#klarna_baloon').width() - 50); position.left = left; jQuery('#klarna_baloon').css(position); jQuery('#klarna_baloon').fadeIn('fast'); } else { var top = position.top - jQuery('#klarna_red_baloon').height(); if (top < 0) top = 10; position.top = top; var left = (position.left + field.width()) - (jQuery('#klarna_red_baloon').width() - 50); position.left = left; jQuery('#klarna_red_baloon').css(position); jQuery('#klarna_red_baloon').fadeIn('fast'); } }); }, saveDates : function (replaceBox) { klarna['select_bday']= jQuery(replaceBox).find('.selectBox_bday').val(); klarna['select_bmonth'] = jQuery(replaceBox).find('.selectBox_bmonth').val(); klarna['select_year'] = jQuery(replaceBox).find('.selectBox_year').val(); }, changeLanguage : function (replaceBox, params, newIso, country, Type) { var paramString = ""; var valueString = ""; data = { action: 'languagepack', subAction: 'klarna_box', type: Type, newIso: newIso, country: country, sum: klarna.sum, fee: klarna.invoice_fee, flag: klarna.flag } // include current field values in request so that the values can be used // in the translation for (var attr in params) { data['params[' + attr + ']'] = params[attr]; var inputValue = jQuery(replaceBox).find('input[name=' + params[attr] + ']').val(); if (typeof inputValue != "undefined") { data['values[' + attr + ']'] = inputValue; } } virtuemart_paymentmethod_id = jQuery(replaceBox).parents('table').find('.klarnaPayment').val(); data['cid'] = virtuemart_paymentmethod_id; klarna.saveDates(replaceBox); jQuery.ajax({ type: "GET", url: klarna.ajaxPath, data: data, success: function(response){ //console.log(response); if (jQuery(response).find('.klarna_box')) { replaceBox.find('.klarna_box').remove(); replaceBox.append(jQuery(response).find('.klarna_box')); if(newIso != klarna.language) replaceBox.find('.klarna_box_bottom_languageInfo').fadeIn('slow', function () { klarna.changeLanguage_busy = false; klarna.language = newIso ; }); else replaceBox.find('.klarna_box_bottom_languageInfo').fadeOut('slow', function () { klarna.changeLanguage_busy = false; }); klarna.methodReady(Type); klarna.initPaymentOptions(replaceBox); } else { alert("Error, block not found. Response:\n\n"+response); } } }); }, methodReady : function (Type) { var foundBox = false; box = jQuery('#klarna_box_'+Type); var currentMinHeight = box.height(); // Select birthdate and fill years box // console.log(Type, klarna.countryCode); if (klarna.countryCode == "de" || klarna.countryCode == "nl") { // Years box var date = new Date(); for (i = date.getFullYear(); i >= 1900; i--) { jQuery('