AAAAklarnacheckout.xml000066600000012607151373700700010301 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.php000066600000164205151373700700010272 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/elements/paymentlogo.php000066600000003410151373700700014432 0ustar00 '; return $logo ; } } }klarnacheckout/elements/vmcountry.php000066600000003126151373700700014146 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/elements/.htaccess000066600000000177151373700700013170 0ustar00 Order allow,deny Deny from all klarnacheckout/elements/getklarnacheckout.php000066600000006725151373700700015606 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/elements/customjs.php000066600000002347151373700700013753 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/elements/getlanguage.php000066600000003106151373700700014361 0ustar00 klarnacheckout/.htaccess000066600000000177151373700700011354 0ustar00 Order allow,deny Deny from all klarnacheckout/library/index.html000066600000000000151373700700013200 0ustar00klarnacheckout/library/.htaccess000066600000000177151373700700013020 0ustar00 Order allow,deny Deny from all klarnacheckout/library/Checkout.php000066600000004160151373700700013474 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/library/Checkout/ConnectorException.php000066600000002575151373700700017315 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/library/Checkout/BasicConnector.php000066600000023242151373700700016372 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/library/Checkout/Exception.php000066600000002535151373700700015436 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/library/Checkout/ConnectionErrorException.php000066600000002637151373700700020473 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/library/Checkout/ConnectorInterface.php000066600000003720151373700700017250 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/library/Checkout/ResourceInterface.php000066600000004070151373700700017104 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/library/Checkout/Order.php000066600000013015151373700700014546 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/library/Checkout/index.html000066600000000000151373700700014745 0ustar00klarnacheckout/library/Checkout/UserAgent.php000066600000005541151373700700015375 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/library/Checkout/HTTP/Transport.php000066600000003147151373700700016253 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/library/Checkout/HTTP/TransportInterface.php000066600000005153151373700700020073 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/library/Checkout/HTTP/index.html000066600000000000151373700700015524 0ustar00klarnacheckout/library/Checkout/HTTP/CURLHeaders.php000066600000004761151373700700016323 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/library/Checkout/HTTP/CURLTransport.php000066600000012411151373700700016733 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/library/Checkout/HTTP/CURLHandleInterface.php000066600000003661151373700700017762 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/library/Checkout/HTTP/Request.php000066600000010605151373700700015704 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/library/Checkout/HTTP/Response.php000066600000007040151373700700016051 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/library/Checkout/HTTP/CURLHandle.php000066600000005055151373700700016140 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/library/Checkout/HTTP/.htaccess000066600000000177151373700700015344 0ustar00 Order allow,deny Deny from all klarnacheckout/library/Checkout/HTTP/CURLFactory.php000066600000003041151373700700016345 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/library/Checkout/Digest.php000066600000003224151373700700014713 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/library/Checkout/Connector.php000066600000003441151373700700015427 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/library/Checkout/.htaccess000066600000000177151373700700014565 0ustar00 Order allow,deny Deny from all klarnacheckout/tmpl/response_received.php000066600000001620151373700700014741 0ustar00
klarnacheckout/tmpl/cart_advertisement.php000066600000002654151373700700015130 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/tmpl/display_payment.php000066600000003445151373700700014446 0ustar00 > klarnacheckout/tmpl/render_pluginname.php000066600000002270151373700700014735 0ustar00 klarnacheckout/tmpl/.htaccess000066600000000177151373700700012330 0ustar00 Order allow,deny Deny from all klarnacheckout/tmpl/order_fe.php000066600000002167151373700700013031 0ustar00
sofort_response_transaction; ?>
klarnacheckout/tmpl/index.html000066600000000057151373700700012524 0ustar00 klarnacheckout/tmpl/show_order.php000066600000001645151373700700013417 0ustar00
klarnacheckout/assets/css/index.html000066600000000000151373700700013626 0ustar00klarnacheckout/assets/css/.htaccess000066600000000177151373700700013446 0ustar00 Order allow,deny Deny from all klarnacheckout/assets/css/klarnacheckout.css000066600000000557151373700700015362 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/assets/index.html000066600000000000151373700700013036 0ustar00klarnacheckout/assets/js/admin.js000066600000001442151373700700013116 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/assets/js/.htaccess000066600000000177151373700700013272 0ustar00 Order allow,deny Deny from all klarnacheckout/assets/js/index.html000066600000000000151373700700013452 0ustar00klarnacheckout/assets/.htaccess000066600000000177151373700700012656 0ustar00 Order allow,deny Deny from all klarnacheckout/index.html000066600000000037151373700700011546 0ustar00 .htaccess000066600000000177151373700700006356 0ustar00 Order allow,deny Deny from all index.html000066600000000037151373700700006550 0ustar00 elements/paymentlogo.php000066600000003410151374421670011443 0ustar00 '; return $logo ; } } }elements/vmcountry.php000066600000003126151374421670011157 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); } }elements/.htaccess000066600000000177151374421670010201 0ustar00 Order allow,deny Deny from all elements/getklarnacheckout.php000066600000006725151374421670012617 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; } }elements/customjs.php000066600000002347151374421670010764 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 ''; } }elements/getlanguage.php000066600000003106151374421670011372 0ustar00 library/index.html000066600000000000151374421670010211 0ustar00library/.htaccess000066600000000177151374421670010031 0ustar00 Order allow,deny Deny from all library/Checkout.php000066600000004160151374421670010505 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'; library/Checkout/ConnectorException.php000066600000002575151374421670014326 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 { }library/Checkout/BasicConnector.php000066600000023242151374421670013403 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); } } library/Checkout/Exception.php000066600000002535151374421670012447 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 { }library/Checkout/ConnectionErrorException.php000066600000002637151374421670015504 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 { } library/Checkout/ConnectorInterface.php000066600000003720151374421670014261 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(); } library/Checkout/ResourceInterface.php000066600000004070151374421670014115 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(); } library/Checkout/Order.php000066600000013015151374421670011557 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" ); } } library/Checkout/index.html000066600000000000151374421670011756 0ustar00library/Checkout/UserAgent.php000066600000005541151374421670012406 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); } } library/Checkout/HTTP/Transport.php000066600000003147151374421670013264 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 ); } } library/Checkout/HTTP/TransportInterface.php000066600000005153151374421670015104 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); } library/Checkout/HTTP/index.html000066600000000000151374421670012535 0ustar00library/Checkout/HTTP/CURLHeaders.php000066600000004761151374421670013334 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; } } library/Checkout/HTTP/CURLTransport.php000066600000012411151374421670013744 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); } } library/Checkout/HTTP/CURLHandleInterface.php000066600000003661151374421670014773 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(); } library/Checkout/HTTP/Request.php000066600000010605151374421670012715 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; } } library/Checkout/HTTP/Response.php000066600000007040151374421670013062 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; } } library/Checkout/HTTP/CURLHandle.php000066600000005055151374421670013151 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); } } library/Checkout/HTTP/.htaccess000066600000000177151374421670012355 0ustar00 Order allow,deny Deny from all library/Checkout/HTTP/CURLFactory.php000066600000003041151374421670013356 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(); } } library/Checkout/Digest.php000066600000003224151374421670011724 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)); } } library/Checkout/Connector.php000066600000003441151374421670012440 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 ); } } library/Checkout/.htaccess000066600000000177151374421670011576 0ustar00 Order allow,deny Deny from all tmpl/response_received.php000066600000001620151374421670011752 0ustar00
tmpl/cart_advertisement.php000066600000002654151374421670012141 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); ?>

tmpl/display_payment.php000066600000003445151374421670011457 0ustar00 > tmpl/render_pluginname.php000066600000002270151374421670011746 0ustar00 tmpl/.htaccess000066600000000177151374421670007341 0ustar00 Order allow,deny Deny from all tmpl/order_fe.php000066600000002167151374421670010042 0ustar00
sofort_response_transaction; ?>
tmpl/index.html000066600000000057151374421670007535 0ustar00 tmpl/show_order.php000066600000001645151374421670010430 0ustar00
assets/css/index.html000066600000000000151374421670010637 0ustar00assets/css/.htaccess000066600000000177151374421670010457 0ustar00 Order allow,deny Deny from all assets/css/klarnacheckout.css000066600000000557151374421670012373 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; }assets/index.html000066600000000000151374421670010047 0ustar00assets/js/admin.js000066600000001442151374421670010127 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(); }); assets/js/.htaccess000066600000000177151374421670010303 0ustar00 Order allow,deny Deny from all assets/js/index.html000066600000000000151374421670010463 0ustar00assets/.htaccess000066600000000177151374421670007667 0ustar00 Order allow,deny Deny from all