/** * @return \Klarna */ protected function getKlarna() { $this->klarna->config($this->config->eid, $this->config->secret, $this->config->country, $this->config->language, $this->config->currency, $this->config->mode); $this->klarna->clear(); $rp = new \ReflectionProperty($this->klarna, 'xmlrpc'); $rp->setAccessible(true); /** @var \xmlrpc_client $xmlrpc */ $xmlrpc = $rp->getValue($this->klarna); $xmlrpc->verifyhost = $this->config->xmlRpcVerifyHost; $xmlrpc->verifypeer = $this->config->xmlRpcVerifyPeer; $rp->setAccessible(false); return $this->klarna; }
/** * Wrapper around remote get_addresses call that caches result in * the session. * * @param string $pno pno to call get_addresses for * * @return array the result of get_addresses or the cached value */ public function getAddresses($pno) { $cache = array(); // Check the session for calls if (array_key_exists(self::$_session_key, $_SESSION)) { $cache = unserialize(base64_decode($_SESSION[self::$_session_key])); } if (array_key_exists($pno, $cache)) { return $cache[$pno]; } $addrs = $this->_api->getAddresses($pno, null, KlarnaFlags::GA_GIVEN); $cache[$pno] = $addrs; $_SESSION[self::$_session_key] = base64_encode(serialize($cache)); return $addrs; }
/** * Initializes this object, this method is always called * before {@link CheckoutHTML::toHTML()}. * This method is used in {@link Klarna::addTransaction()}, * {@link Klarna::reserveAmount()} and in {@link Klarna::checkoutHTML()} * * @param Klarna $klarna The API instance * @param int $eid Merchant ID * * @return void */ public function init($klarna, $eid) { if (!is_int($eid)) { throw new Klarna_ConfigFieldMissingException('eid'); } if (isset($_SESSION)) { if (!isset($_SESSION[self::ID]) || strlen($_SESSION[self::ID]) < 40) { $_SESSION[self::ID] = parent::getSessionID($eid); $this->sessionID = $_SESSION[self::ID]; } else { $this->sessionID = $_SESSION[self::ID]; } } else { $this->sessionID = parent::getSessionID($eid); } $klarna->setSessionID(self::ID, $this->sessionID); }
/** * Returns the klarna transaction id. * * @return string */ protected function getKlarnaTransactionId() { $orderNumber = $this->order['number']; try { if ($this->pluginExists('PigmbhKlarnaPayment')) { // eid / shop_id $sql = 'SELECT shop_id FROM Pi_klarna_payment_multistore WHERE order_number = ?'; $multistore = Shopware()->Db()->query($sql, array($orderNumber))->fetchObject(); // pclass $sql = 'SELECT pclassid FROM Pi_klarna_payment_pclass where ordernumber = ?'; $pclass = Shopware()->Db()->query($sql, array($orderNumber))->fetchObject(); // Transaction ID $sql = 'SELECT transactionid FROM Pi_klarna_payment_order_data WHERE order_number = ?'; $order = Shopware()->Db()->query($sql, array($orderNumber))->fetchObject(); return sprintf('%s_%s_%s', $order->transactionid, $pclass->pclassid, $multistore->shop_id); } elseif ($this->pluginExists('SwagPaymentKlarna') || $this->pluginExists('SwagPaymentKlarnaKpm')) { /* * @var Klarna $klarna */ $this->klarnaService = Shopware()->Container()->get('KlarnaService'); if (!empty($this->order['languageIso'])) { $this->klarnaService->setLanguage($this->order['languageIso']); } else { throw new Exception('order language missing'); } if (!empty($this->order['billing']['country']['iso'])) { $this->klarnaService->setCountry($this->order['billing']['country']['iso']); } else { throw new Exception('order country missing'); } if (!empty($this->order['currency'])) { $this->klarnaService->setCurrency($this->order['currency']); } else { throw new Exception('order currency missing'); } /** * @var KlarnaPClass */ $pclass = $this->getKlarnaPClass(); if (!empty($pclass)) { if (isset($this->order['payment']['name']) && $this->order['payment']['name'] == 'klarna_invoice') { $classId = KlarnaPClass::INVOICE; } else { $classId = $pclass->getId(); } return sprintf('%s_%s_%s', $this->order['transactionId'], $classId, $pclass->getEid()); } else { throw new Exception('No compatible pclass found'); } } else { throw new Exception('No compatible Klarna payment plugin found'); } } catch (Exception $e) { PyLog()->error('Sync:Order:PaymentKlarna', $e->getMessage()); } return ''; }
/** * 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 vmText::_('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 = @vmText::_($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!'); } } } } }
/** * Match an address from the checkout with an address from getAddress, and * return the matching address. * * @param array &$errors reference to errors array * @param string $option payment method * * @return object KlarnaAddr object */ public function getMatchingAddress(&$errors, $option) { $addrs = array(); $pno = $_POST["klarna_{$option}_pno"]; $_SESSION['klarna_data']['pno'] = $pno; $_SESSION['klarna_data']['phone'] = $_POST["klarna_{$option}_phone_number"]; $address = new KlarnaAddr(); $KITTaddr = new KiTT_Addresses(KiTT::api('SE')); try { $address = $KITTaddr->getMatchingAddress($pno, $_POST["klarna_{$option}_address_key"]); $address->setTelno($_POST["klarna_{$option}_phone_number"]); $address->setCellno($_POST["klarna_{$option}_phone_number"]); $address->setEmail($_POST["klarna_email"]); } catch (Exception $e) { Klarna::printDebug('Error in __METHOD__', $e->getMessage()); $errors[] = "error_no_address"; } return $address; }
/** * The constructor * * @param int|string $country country * * @return void */ public function __construct($country = null) { global $currency; $this->_country = KlarnaUtils::deduceCountry('part'); $this->_language = KlarnaUtils::getLanguageCode(); $this->_currency = $currency; if ($country === null && $this->_country == null) { $this->_country = strtoupper($_SESSION['language_code']); } if ($this->_country === null) { Klarna::printDebug(__METHOD__, array('currency' => $this->_currency, 'language' => $this->_language)); $this->_enabled = false; return; } $this->_utils = new KlarnaUtils($this->_country); $this->_enabled = KlarnaConstant::isEnabled('part', $this->_country); if ($this->_enabled === true && !KlarnaConstant::isActivated('part', $this->_country)) { $this->_enabled = false; } $this->_locale = KiTT::locale($this->_country, $this->_language, $this->_currency); }
/** * Update orderstatuses in the database * * @param int $customer The order status id to show the customer * @param int $admin The order status id to show in the administration page * * @return void */ public function updateOrderDatabase($customer, $admin) { global $insert_id; $orderid = mysqli_real_escape_string(xtc_db_connect(), $insert_id); $refno = mysqli_real_escape_string(xtc_db_connect(), $_SESSION['klarna_refno']); $sql_data_arr = array('orders_id' => $orderid, 'orders_status_id' => $customer, 'comments' => "Accepted by Klarna. Reference #: {$refno}", 'customer_notified' => 1, 'date_added' => date("Y-m-d H:i:s")); xtc_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_arr); $has_ordernum_table = xtc_db_fetch_array(xtc_db_query("SELECT COUNT(*) " . "FROM information_schema.tables " . "WHERE table_schema = '" . DB_DATABASE . "' " . "AND table_name = 'klarna_ordernum';")); $has_ordernum_table = $has_ordernum_table['COUNT(*)']; if ($has_ordernum_table > 0) { xtc_db_query("INSERT INTO `klarna_ordernum` (orders_id, klarna_ref) " . "VALUES ({$orderid}, {$refno})"); } // Set pending status and hide it from customer. $status = $_SESSION['klarna_orderstatus']; if (isset($status)) { $orderStatusQuery = $this->_klarnaDB->query("SELECT orders_status_id FROM " . TABLE_ORDERS_STATUS . " WHERE orders_status_name = '{$status}'"); $orderStatusID = $orderStatusQuery->getArray(); $sql_data_arr = array('orders_id' => $orderid, 'orders_status_id' => $orderStatusID['orders_status_id'], 'comments' => "Klarna Orderstatus: {$status}", 'customer_notified' => 0, 'date_added' => date("Y-m-d H:i:s")); xtc_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_arr); xtc_db_query("UPDATE " . TABLE_ORDERS . " SET orders_status='" . $orderStatusID['orders_status_id'] . "' WHERE orders_id='" . $orderid . "'"); } try { $this->_klarna->setEstoreInfo(KiTT_String::encode($orderid)); $this->_klarna->update($_SESSION['klarna_refno']); } catch (Exception $e) { Klarna::printDebug(__METHOD__, "{$e->getMessage()} #({$e->getCode()})"); } //Delete Session with user details unset($_SESSION['klarna_data']); unset($_SESSION['klarna_refno']); unset($_SESSION['klarna_orderstatus']); }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); $rno = '2347666470'; try { $status = $k->checkOrderStatus($rno); // $status is KlarnaFlags::ACCEPTED, KlarnaFlags::DENIED or KlarnaFlags::PENDING echo "OK: order status {$status}\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); $invNo = '123456'; try { $k->sendInvoice($invNo); echo "OK\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
/** * Sets the country, use either a two letter representation or the integer constant. * * @param int $country {@link KlarnaCountry} * @throws KlarnaException * @return void */ public function setCountry($country) { if(!is_numeric($country) && strlen($country) == 2) { $this->setCountry(Klarna::getCountryForCode($country)); } else { if(!isset($country)) { throw new KlarnaException("Error in " . __METHOD__ . ": Country is not set!"); } if(is_numeric($country) && !is_int($country)) { $country = intval($country); } if(!is_numeric($country) || !is_int($country)) { throw new KlarnaException("Error in " . __METHOD__ . ": Country not an integer! ($country)"); } $this->country = $country; } }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); try { $ocrs = $k->reserveOCR(1); // $ocrs is a list of string OCR numbers. echo "OK\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
/** * Converts special characters to numeric htmlentities. * * <b>Note</b>:<br> * If supplied string is encoded with UTF-8, o umlaut ("�") will become two HTML entities instead of one. * * @param string $str String to be converted. * @return string String converted to numeric HTML entities. */ public static function num_htmlentities($str) { if (!self::$htmlentities) { self::$htmlentities = array(); foreach (get_html_translation_table(HTML_ENTITIES, ENT_QUOTES) as $char => $entity) { self::$htmlentities[$entity] = '&#' . ord($char) . ';'; } } return str_replace(array_keys(self::$htmlentities), self::$htmlentities, htmlentities($str)); }
/** * Update list of pclasses * * @param int $sum order total for filtering * @param int $page PRODUCT_PAGE or CHECKOUT_PAGE * @param array $types PClass types to include * * @return void */ public function update($sum, $page, $types) { $pclasses = array(); $default = null; $minimum = null; $minval = null; foreach ($this->_kapi->getPClasses() as $pclass) { $type = $pclass->getType(); if (!in_array($type, $types) || $sum < $pclass->getMinAmount()) { continue; } // Get monthly cost if (in_array($type, array(KlarnaPClass::FIXED, KlarnaPClass::SPECIAL))) { if ($page == KlarnaFlags::PRODUCT_PAGE) { continue; } $monthlyCost = -1; } else { $lowestPayment = KlarnaCalc::get_lowest_payment_for_account($pclass->getCountry()); $monthlyCost = KlarnaCalc::calc_monthly_cost($sum, $pclass, $page); if ($monthlyCost < 0.01) { continue; } if ($monthlyCost < $lowestPayment) { if ($pclass->getType() == KlarnaPClass::CAMPAIGN) { continue; } if ($page == KlarnaFlags::CHECKOUT_PAGE && $pclass->getType() == KlarnaPClass::ACCOUNT) { $monthlyCost = $lowestPayment; } } } // Select the minimum if ($minimum === null || $minval > $monthlyCost) { $minimum = $pclass; $minval = $monthlyCost; } // Select the default if ($type == KlarnaPClass::ACCOUNT) { $default = $pclass; } else { if ($type == KlarnaPClass::CAMPAIGN) { if ($default === null || $default->getType() != KlarnaPClass::ACCOUNT) { $default = $pclass; } } else { if ($default === null) { $default = $pclass; } } } $pclasses[$pclass->getId()] = array('pclass' => $pclass, 'locale' => new KiTT_Locale($pclass->getCountry()), 'monthlyCost' => $monthlyCost); } // Save result $this->pclasses = $pclasses; if ($default != null) { $this->_default = $default; } if ($minimum != null) { $this->_minimum = $minimum; } }
public function __construct() { $this->VERSION = 'PHP' . phpversion() . ':VirtueMart:2.0.12f'; Klarna::$debug = false; }
/** * Get the headers associated to this request * * @return array Array of headers strings */ public function getHeaders() { $digest = Klarna::digest(Klarna::colon($this->config['eid'], $this->params['currency'], $this->config['secret'])); return array("Accept: {$this->accept}", "Authorization: xmlrpc-4.2 {$digest}"); }
public function setPayment($type) { $address_invoice = new Address((int) $this->context->cart->id_address_invoice); $country = new Country((int) $address_invoice->id_country); $currency = new Currency((int) $this->context->cart->id_currency); if (!$this->verifCountryAndCurrency($country, $currency)) { return false; } $klarna = new Klarna(); $klarnaInt = new KlarnaIntegration($klarna); $klarna->config(Configuration::get('KLARNA_STORE_ID_' . $this->countries[$country->iso_code]['name']), Configuration::get('KLARNA_SECRET_' . $this->countries[$country->iso_code]['name']), $this->countries[$country->iso_code]['code'], $this->countries[$country->iso_code]['langue'], $this->countries[$country->iso_code]['currency'], Configuration::get('KLARNA_MOD'), 'mysql', $this->_getDb()); if ($type == 'invoice' && Configuration::get('KLARNA_INVOICE_FEE_' . $this->countries[$country->iso_code]['name']) > 0 && !$this->isInCart($this->context->cart, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name']))) { $this->context->cart->updateQty(1, (int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); $productInvoicefee = new Product((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); $productInvoicefee->addStockMvt(1, 1); $productInvoicefee->update(); } $this->initReservation($klarna, $this->context->cart, $this->context->customer, isset($_POST['klarna_house_number']) ? htmlentities($_POST['klarna_house_number'], ENT_QUOTES, 'ISO-8859-1') : null, isset($_POST['klarna_house_ext']) ? htmlentities($_POST['klarna_house_ext'], ENT_QUOTES, 'ISO-8859-1') : null); if (Tools::isSubmit('klarna_pno')) { $pno = Tools::safeOutput(Tools::getValue('klarna_pno')); } else { $day = $_POST['klarna_pno_day'] < 10 ? '0' . (int) $_POST['klarna_pno_day'] : (int) $_POST['klarna_pno_day']; $month = $_POST['klarna_pno_month'] < 10 ? '0' . (int) $_POST['klarna_pno_month'] : (int) $_POST['klarna_pno_month']; $pno = Tools::safeOutput($day . $month . Tools::getValue('klarna_pno_year')); } $pclass = $type == 'invoice' ? KlarnaPClass::INVOICE : (int) Tools::getValue('paymentAccount'); try { if ($country->iso_code == 'DE' || $country->iso_code == 'NL') { if ($this->context->customer->id_gender != 1 && $this->context->customer->id_gender != 2 && $this->context->customer->id_gender != 3) { $gender = (int) $_POST['klarna_gender']; $customer = new Customer($this->context->customer->id); $customer->id_gender = (int) $_POST['klarna_gender']; $Customer->birthday = (int) $_POST['klarna_pno_year'] . '-' . $month . '-' . $day; $customer->update(); } else { $gender = $this->context->customer->id_gender == 1 ? 1 : 0; } } else { $gender = null; } $result = $klarnaInt->reserve($pno, $gender, -1, KlarnaFlags::NO_FLAG, (int) $pclass); // Here we get the reservation number or invoice number $rno = $result[0]; Db::getInstance()->autoExecute(_DB_PREFIX_ . 'klarna_rno', array('id_cart' => (int) $this->context->cart->id, 'rno' => pSQL($rno), 'pno' => pSQL($pno), 'house_number' => isset($_POST['klarna_house_number']) ? pSQL($_POST['klarna_house_number']) : null, 'house_ext' => isset($_POST['klarna_house_ext']) ? pSQL($_POST['klarna_house_ext']) : null, 'state' => self::RESERVED, 'type' => pSQL($type), 'pclass' => $type == 'invoice' ? null : (int) Tools::getValue('paymentAccount')), 'INSERT'); $updateResult = $klarnaInt->updateOrderNo($rno, (int) $this->context->cart->id); if ($result[1] == KlarnaFlags::PENDING) { $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_PENDING'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key); } else { if ($result[1] == KlarnaFlags::ACCEPTED) { $this->validateOrder((int) $this->context->cart->id, Configuration::get('KLARNA_PAYMENT_ACCEPTED'), (double) $this->context->cart->getOrderTotal(), $this->displayName, null, array(), null, false, $this->context->cart->secure_key); } } $redirect = __PS_BASE_URI__ . 'index.php?controller=order-confirmation&id_cart=' . (int) $this->context->cart->id . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $this->context->cart->secure_key; header('Location: ' . $redirect); exit; } catch (Exception $e) { /*remove invoiceFee if existe*/ $this->context->cart->deleteProduct((int) Configuration::get('KLARNA_INV_FEE_ID_' . $this->countries[$country->iso_code]['name'])); return array('error' => true, 'message' => Tools::safeOutput(utf8_encode($e->getMessage()))); } }
/** * Fetches PClass * * @param String $piKlarnaEid ShopId * @param String $piKlarnaSecret ShopSecret * * @return String Result message */ function piKlarnaFetchKlarnaPClass($piKlarnaEid, $piKlarnaSecret) { if ($piKlarnaEid && $piKlarnaSecret) { require_once dirname(__FILE__) . '/../api/Klarna.php'; require_once dirname(__FILE__) . '/../api/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(__FILE__) . '/../api/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE); $piKlarnaConfig = Shopware()->Plugins()->Frontend()->PigmbhKlarnaPayment()->Config(); // $sql = "SELECT shopID FROM s_core_plugin_configs WHERE name LIKE 'pi_klarna_Merchant_ID' AND value like ?"; // $piKlarnaShopId = Shopware()->Db()->fetchOne($sql, array("%" . $piKlarnaEid . "%")); // if($piKlarnaShopId){ // $sql = "SELECT value FROM s_core_plugin_configs WHERE name LIKE 'pi_klarna_liveserver' AND shopID = ?"; // $piKlarnaLivecheck = $piKlarnaConfig->pi_klarna_liveserver; // $piKlarnaLivecheckSub = substr($piKlarnaLivecheck, -3, -2); if ($piKlarnaConfig->pi_klarna_liveserver) { $mymode = Klarna::LIVE; } else { $mymode = Klarna::BETA; } $countrys=Array(81,59,73,154,164,209); $currencys=Array(2,3,2,2,1,0); $languages=Array(28,37,97,101,27,138); $countryNames=Array('Deutschland','Dänemark','Finnland','Niederlande','Norwegen','Schweden'); $counter=0; $errortext=""; $piKlarnaErrorText=""; for($i=0;$i<count($countrys);$i++){ $k = new Klarna(); $k->config( $piKlarnaEid, $piKlarnaSecret, KlarnaCountry::DE, KlarnaLanguage::DE, KlarnaCurrency::EUR, $mymode, 'json', dirname(__FILE__) . '/../classes/Pclass_' . $piKlarnaEid . '.php', true, true ); try{ if($i==0)$piKlarnaErrorText='Ratenzahlungsmodalitäten für folgende Länder gespeichert: <br />'; $k->fetchPClasses($countrys[$i],$languages[$i],$currencys[$i]); $counter++; $piKlarnaErrorText .= "<b>" . $countryNames[$i] . "</b>"; $piKlarnaErrorText .=", "; } catch(Exception $e){ $errortext= $e->getMessage(). ' (#' . $e->getCode() . ')'; } } $rest = substr($piKlarnaErrorText, 0, -2); if($counter==0) return $errortext; else return $rest; } }
/** * @see CheckoutHTML::toHTML() * @param Klarna $klarna The API instance * @param int $eid * @return void */ public function init($klarna, $eid) { if (!is_int($eid)) { throw new KlarnaException('Error in ' . __METHOD__ . ': eid is not an integer!'); } if (isset($_SESSION)) { if (!isset($_SESSION[self::ID]) || strlen($_SESSION[self::ID]) < 40) { $_SESSION[self::ID] = parent::getSessionID($eid); $this->sessionID = $_SESSION[self::ID]; } else { $this->sessionID = $_SESSION[self::ID]; } } else { $this->sessionID = parent::getSessionID($eid); } $klarna->setSessionID(self::ID, $this->sessionID); }
function getKlarnaAddress() { if (JVM_VERSION >= 2) { require_once JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'klarna.php'; require_once JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'klarna' . DS . 'api' . DS . 'klarnaaddr.php'; } else { require_once JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna.php'; require_once JPATH_ROOT . DS . 'plugins' . DS . 'vmpayment' . DS . 'klarna' . DS . 'api' . DS . 'klarnaaddr.php'; } $klarna = new Klarna(); $q = "select * from #__virtuemart_paymentmethods where payment_element = 'klarna' and published = '1' limit 0,1"; $db = JFactory::getDBO(); $db->setQuery($q); $res = $db->loadAssoc(); if (empty($res)) { return null; } $id = $res['virtuemart_paymentmethod_id']; jimport('joomla.html.parameter'); $params = explode('|', $res['payment_params']); $obj = new stdclass(); foreach ($params as $item) { $item = explode('=', $item); $key = $item[0]; unset($item[0]); $item = implode('=', $item); if (!empty($item)) { $obj->{$key} = @json_decode($item); } } $cData = KlarnaHandler::countryData($obj, 'SWE'); $language = KlarnaLanguage::fromCode('SE'); $currency = KlarnaCurrency::fromCode($cData['currency_code']); $klarna->config($cData['eid'], $cData['secret'], $cData['country_code'], $language, $currency, $cData['mode']); /* $country = JRequest::getVar('virtuemart_country_id', ''); if (!empty($country) && (is_numeric($country))) { $q = 'select * from #__virtuemart_countries where virtuemart_country_id = '.$country.' limit 0,1'; $db->setQuery($q); $r = $db->loadAssoc(); $e = $db->getErrorMsg(); if (empty($r)) $c = 'se'; else $c = strtolower($r['country_2_code']); } else */ $c = 'se'; $klarna->setCountry($c); $klarna->setLanguage($language); $klarna->setCurrency($currency); //Attempt to get the address(es) associated with the SSN/PNO. $pn = JRequest::getVar('socialNumber', ''); $addrs = $klarna->getAddresses($pn); if (empty($addrs)) { return null; } $a = array(); foreach ($addrs as $key => $addr) { $a = $addr->toArray(); foreach ($a as $k => $v) { $a[$k] = utf8_encode($v); } return $a; //if (empty($ar)) return null; if ($addr->isCompany) { $a['company_name'] = $addr->getCompanyName(); } else { $a['company_name'] = ''; } $a['first_name'] = $addr->getFirstName(); $a['last_name'] = $addr->getLastName(); $a['address_1'] = $addr->getStreet(); $a['email'] = $addr->getEmail(); $a['phone_1'] = $addr->getTelno(); $a['phone_2'] = $addr->getCellno(); $a['address_2'] = $addr->getHouseExt(); $a['zip'] = $addr->getZipCode(); $a['city'] = $addr->getCity(); return $a; } return null; /* If there exists several addresses you would want to output a list in which the customer could choose the address which suits him/her. */ // Print them if available: foreach ($addrs as $key => $addr) { echo "<table>\n"; // This only works if the right getAddresses type is used. if ($addr->isCompany) { echo "\t<tr><td>Company</td><td> {$addr->getCompanyName()} </td></tr>\n"; } else { echo "\t<tr><td>First name</td><td>{$addr->getFirstName()}</td></tr>\n"; echo "\t<tr><td>Last name</td><td>{$addr->getLastName()}</td></tr>\n"; } echo "\t<tr><td>Street</td><td>{$addr->getStreet()}</td></tr>\n"; echo "\t<tr><td>Zip code</td><td>{$addr->getZipCode()}</td></tr>\n"; echo "\t<tr><td>City</td><td>{$addr->getCity()}</td></tr>\n"; echo "\t<tr><td>Country</td><td>{$addr->getCountryCode()}</td></tr>\n"; echo "</table>\n"; } //Something went wrong return null; echo "{$e->getMessage()} (#{$e->getCode()})\n"; return null; return null; }
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 = "<?xml version='1.0'" . "?" . ">\n"; //eval breaks at question-mark gt $sString .= "<getAddress>\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 .= "<address>\n"; foreach ($implode as $key => $val) { $sString .= "<" . $key . ">" . Klarna::num_htmlentities($val) . "</" . $key . ">\n"; } $sString .= "</address>\n"; } $sString .= "</getAddress>"; return array('type' => 'text/xml', 'value' => $sString); }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); $k->addArticle(4, "MG200MMS", "Matrox G200 MMS", 299.99, 25, 0, KlarnaFlags::INC_VAT); $k->addArticle(1, "", "Shipping fee", 14.5, 25, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT); $k->addArticle(1, "", "Handling fee", 11.5, 25, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING); $addr = new KlarnaAddr('*****@*****.**', '', '0762560000', 'Testperson-se', 'Approved', '', 'Stårgatan 1', '12345', 'Ankeborg', KlarnaCountry::SE, null, null); $k->setAddress(KlarnaFlags::IS_BILLING, $addr); $k->setAddress(KlarnaFlags::IS_SHIPPING, $addr); try { $result = $k->reserveAmount('4103219202', null, -1, KlarnaFlags::NO_FLAG, KlarnaPClass::INVOICE); $rno = $result[0]; $status = $result[1]; // $status is KlarnaFlags::PENDING or KlarnaFlags::ACCEPTED. echo "OK: reservation {$rno} - order status {$status}\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); $rno = '123456'; try { $result = $k->activate($rno, null, KlarnaFlags::RSRV_SEND_BY_EMAIL); // For optional arguments, flags, partial activations and so on, refer to the documentation. // See Klarna::setActivateInfo $risk = $result[0]; // "ok" or "no_risk" $invNo = $result[1]; // "9876451" echo "OK: invoice number {$invNo} - risk status {$risk}\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); try { $k->fetchPClasses(); $pclasses = $k->getAllPClasses(); // $pclasses is now a list of KlarnaPClass instances. echo "OK\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
public function getMonthlyCoast($cart, $countries, $country) { if (!$this->klarna->active) { return; } $klarna = new Klarna(); $klarna->config(Configuration::get('KLARNA_STORE_ID_' . $countries[$country->iso_code]['name']), Configuration::get('KLARNA_SECRET_' . $countries[$country->iso_code]['name']), $countries[$country->iso_code]['code'], $countries[$country->iso_code]['langue'], $countries[$country->iso_code]['currency'], Configuration::get('KLARNA_MOD'), 'mysql', array('user' => _DB_USER_, 'passwd' => _DB_PASSWD_, 'dsn' => _DB_SERVER_, 'db' => _DB_NAME_, 'table' => _DB_PREFIX_ . 'klarna_payment_pclasses')); $accountPrice = array(); $pclasses = array_merge($klarna->getPClasses(KlarnaPClass::ACCOUNT), $klarna->getPClasses(KlarnaPClass::CAMPAIGN)); $total = (double) $cart->getOrderTotal(); foreach ($pclasses as $val) { if ($val->getMinAmount() < $total) { $accountPrice[$val->getId()] = array('price' => KlarnaCalc::calc_monthly_cost($total, $val, KlarnaFlags::CHECKOUT_PAGE), 'month' => (int) $val->getMonths(), 'description' => htmlspecialchars_decode(Tools::safeOutput($val->getDescription()))); } } return $accountPrice; }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); $k->setCountry('se'); // Sweden only try { $addrs = $k->getAddresses('410321-9202'); // $addrs is a list of KlarnaAddr instances. echo "OK\n"; } catch (Exception $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
public function __construct() { $this->VERSION = 'PHP:VirtueMart2:' . KLARNA_MODULE_VERSION . ':r74'; Klarna::$debug = false; }
/** * Ajax request callback function */ function ajax_request() { // The $_REQUEST contains all the data sent via ajax if (isset($_REQUEST)) { if ('' != $this->partpay_eid && '' != $this->partpay_secret) { $klarna_eid = $this->partpay_eid; $klarna_secret = $this->partpay_secret; $klarna_testmode = $this->partpay_testmode; } elseif ('' != $this->invo_eid && '' != $this->invo_secret) { $klarna_eid = $this->invo_eid; $klarna_secret = $this->invo_secret; $klarna_testmode = $this->invo_testmode; } // Test mode or Live mode if ($klarna_testmode == 'yes') { // Disable SSL if in testmode $klarna_ssl = 'false'; $klarna_mode = Klarna::BETA; } else { // Set SSL if used in webshop if (is_ssl()) { $klarna_ssl = 'true'; } else { $klarna_ssl = 'false'; } $klarna_mode = Klarna::LIVE; } $k = new Klarna(); $k->config($klarna_eid, $klarna_secret, 'SE', 'SE', get_woocommerce_currency(), $klarna_mode, $pcStorage = 'json', $pcURI = '/srv/pclasses.json'); $pno_getadress = $_REQUEST['pno_getadress']; $return = array(); $k->setCountry('SE'); // Sweden only try { $addrs = $k->getAddresses($pno_getadress); foreach ($addrs as $addr) { //$return[] = $addr->toArray(); $return[] = array('email' => utf8_encode($addr->getEmail()), 'telno' => utf8_encode($addr->getTelno()), 'cellno' => utf8_encode($addr->getCellno()), 'fname' => utf8_encode($addr->getFirstName()), 'lname' => utf8_encode($addr->getLastName()), 'company' => utf8_encode($addr->getCompanyName()), 'careof' => utf8_encode($addr->getCareof()), 'street' => utf8_encode($addr->getStreet()), 'zip' => utf8_encode($addr->getZipCode()), 'city' => utf8_encode($addr->getCity()), 'country' => utf8_encode($addr->getCountry())); } } catch (Exception $e) { // $message = "{$e->getMessage()} (#{$e->getCode()})\n"; $return = $e; $return = array('get_address_message' => __('No address found', 'woocommerce-gateway-klarna')); } wp_send_json($return); // If you're debugging, it might be useful to see what was sent in the $_REQUEST // print_r($_REQUEST); } else { echo ''; die; } die; }
public function __construct() { $this->VERSION = 'PHP' . phpversion() . ':3.0.6.2'; Klarna::$debug = false; }
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; $k = new Klarna(); $k->config(0, 'sharedSecret', KlarnaCountry::SE, KlarnaLanguage::SV, KlarnaCurrency::SEK, Klarna::BETA, 'json', './pclasses.json'); // Replace cart with new items $k->addArticle(4, "MG200MMS", "Matrox G200 MMS", 299.99, 25, 0, KlarnaFlags::INC_VAT); $k->addArticle(1, "", "Shipping fee", 14.5, 25, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT); $k->addArticle(1, "", "Handling fee", 11.5, 25, 0, KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING); // For information on what else you can update, refer to the documentation $rno = '123456'; try { $k->update($rno); echo "OK\n"; } catch (KlarnaException $e) { echo "{$e->getMessage()} (#{$e->getCode()})\n"; }