Standard Integration

Below you will find the functions used to set up a standard integration.

Please note! All input data strings should be encoded in accordance with ISO-8859-1

 

 

  This function is used to...
addTransaction Create the passive invoice, contains information about the customer (address, date of birth) and the purchase (goods and prices).
deleteInvoice Remove a passive invoice from our system.
activateInvoice Activate the passive invoice that was created with the add_transaction.
activatePart Partially activate a purchase, used if you have goods that will be delivered at a later date.

 


addTransaction

Purpose:

The addTransaction function is used to create an invoice.

Return value:

Array - [invno, invoiceStatus]
The value of "invno" is the invoice number for the purchase, at most 255 char string
The value of "invoiceStatus" shows if the invoice can be delivered immediately or requires manual approval. 
1 = OK
2 = Pending

or

Throws an exception with error code and error message.

<?php

require_once dirname(dirname(__FILE__)) . '/Klarna.php';

// Dependencies from http://phpxmlrpc.sourceforge.net/
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc';

/**
 * 1. Initialize and setup the Klarna instance.
 */

$k = new Klarna();

$k->config(
    123456,               // Merchant ID
    'sharedSecret',       // Shared Secret
    KlarnaCountry::SE,    // Country
    KlarnaLanguage::SV,   // Language
    KlarnaCurrency::SEK,  // Currency
    Klarna::BETA,         // Server
    'json',               // PClass Storage
    '/srv/pclasses.json', // PClass Storage URI path
    true,                 // SSL
    true                  // Remote logging of response times of xmlrpc calls
);

// OR you can set the config to loads from a file, for example /srv/klarna.json:
// $k->setConfig(new KlarnaConfig('/srv/klarna.json'));

/**
 * 2. Add the article(s), shipping and/or handling fee.
 */

// Here we add a normal product to our goods list.
$k->addArticle(
    4,                      // Quantity
    "MG200MMS",             // Article number
    "Matrox G200 MMS",      // Article name/title
    299.99,                 // Price
    25,                     // 25% VAT
    0,                      // Discount
    KlarnaFlags::INC_VAT    // Price is including VAT.
);

// Next we might want to add a shipment fee for the product
$k->addArticle(
    1,
    "",
    "Shipping fee",
    14.5,
    25,
    0,
    // Price is including VAT and is shipment fee
    KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT
);

// Lastly, we want to use an invoice/handling fee as well
$k->addArticle(
    1,
    "",
    "Handling fee",
    11.5,
    25,
    0,
    // Price is including VAT and is handling/invoice fee
    KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING
);

/**
 * 3. Create and set the address(es).
 */

// Create the address object and specify the values.
$addr = new KlarnaAddr(
    'always_approved@klarna.com', // email
    '',                           // Telno, only one phone number is needed.
    '0762560000',                 // Cellno
    'Testperson-se',              // Firstname
    'Approved',                   // Lastname
    '',                           // No care of, C/O.
    'Stårgatan 1',                // Street
    '12345',                      // Zip Code
    'Ankeborg',                   // City
    KlarnaCountry::SE,            // Country
    null,                         // HouseNo for German and Dutch customers.
    null                          // House Extension. Dutch customers only.
);

// Next we tell the Klarna instance to use the address in the next order.
$k->setAddress(KlarnaFlags::IS_BILLING, $addr);  // Billing / invoice address
$k->setAddress(KlarnaFlags::IS_SHIPPING, $addr); // Shipping / delivery address

/**
 * 4. Specify relevant information from your store. (OPTIONAL)
 */

// Set store specific information so you can e.g. search and associate invoices
// with order numbers.
$k->setEstoreInfo(
    '175012',       // Order ID 1
    '1999110234',   // Order ID 2
    ''              // Optional username, email or identifier
);

// If you don't have the order id available at this stage, you can later use the
// method updateOrderNo().

/**
 * 5. Set additional information. (OPTIONAL)
 */

/** Comment **/

$k->setComment('A text string stored in the invoice commentary area.');

/** Shipment type **/

// Normal shipment is defaulted, delays the start of invoice expiration/due-date.
$k->setShipmentInfo('delay_adjust', KlarnaFlags::EXPRESS_SHIPMENT);


/**
 * 6. Invoke addTransaction and transmit the data.
 */

try {
    // Transmit all the specified data, from the steps above, to Klarna.
    $result = $k->addTransaction(
        '4103219202',             // PNO (Date of birth for DE and NL).
        null,                   // Gender.
        KlarnaFlags::NO_FLAG,   // Flags to affect behavior.
        // -1, notes that this is an invoice purchase, for part payment purchase
        // you will have a pclass object on which you use getId().
        KlarnaPClass::INVOICE
    );

    // Check the order status
    if ($result[1] == KlarnaFlags::PENDING) {
        /* The order is under manual review and will be accepted or denied at a
           later stage. Use cronjob with checkOrderStatus() or visit Klarna
           Online to check to see if the status has changed. You should still
           show it to the customer as it was accepted, to avoid further attempts
           to fraud.
         */
    }

    // Here we get the invoice number
    $invno = $result[0];

    // Order is complete, store it in a database.
    echo "Status: {$result[1]}\nInvno: {$result[0]}\n";
} catch(Exception $e) {
    // The purchase was denied or something went wrong, print the message:
    echo "{$e->getMessage()} (#{$e->getCode()})\n";
    echo $e->getTraceAsString();
}
<%
    Option Explicit
%>
<!-- Please note that the include below points to the web root -->
<!-- The include has to be modified if example is placed elsewhere -->
<!-- #include virtual="Klarna.asp" -->
<!-- 1. Initialize and setup the Klarna instance -->
<%
    ' Grab the API object
    ' -Merchant ID or Estore ID, an integer above 0.
    ' -The shared secret which accompanied your eid.
    ' -Country, language and currency.
    Dim kAPI
    Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")

    ' Do we want to see normal debug information?
    kAPI.DebugInformation = True

    ' Set the address and port to Klarna server.
    ' Use LIVE or BETA depending on which server your eid is associated with.
    kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
    kAPI.SetHost(BETA_HOST) ' or LIVE_HOST

    ' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
    kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))

%>
<!-- 2. Add the article(s), shipping and/or handling fee -->
<%

    ' Here we add a normal product to our goods list.
    ' -Quantity
    ' -Article number
    ' -Article name/title
    ' -Price
    ' -VAT, 25% VAT
    ' -Discount
    ' -Flags, price including VAT
    Call kAPI.AddArticle(4, "MG200MMS", "Matrox G200 MMS", 299.99, 25, 0, INC_VAT)

    ' Next we might want to add a shipment fee for the product
    Call kAPI.AddArticle(1, "", "Shipping fee", 40, 25, 0, INC_VAT + IS_SHIPMENT)

    ' Lastly, we want to use an invoice/handling fee as well
    Call kAPI.AddArticle(1, "", "Handling fee", 10, 25, 0, INC_VAT + IS_HANDLING)

%>
<!-- 3. Create and set the address(es) -->
<%

    ' Create the address object.
    Dim address
    Set address = new KlarnaAddr

    ' Specify the customers details.
    address.setEmail("always_accepted@klarna.se")
    address.setTelno("") ' We skip the normal land line phone, only one is needed.
    address.setCellno("0765260000")
    address.setFirstName("Testperson-se")
    address.setLastName("Approved")
    address.setCompanyName("") ' No company name
    address.setCareof("") ' No care of, C/O
    address.setStreet("Stårgatan 1") ' For DE and NL specify street number with setHouseNumber.
    address.setHouseNumber("") ' Only required for DE / NL
    address.setHouseExt("") ' Only required for NL.
    address.setZipCode("12345")
    address.setCity("Ankeborg")
    address.setCountry(COUNTRY_SE)

    ' Next we tell the Klarna instance to use the address in the next order.
    Call kAPI.SetAddress(IS_BILLING, address)  ' Billing / invoice address
    Call kAPI.SetAddress(IS_SHIPPING, address) ' Shipping / delivery address

%>
<!-- 4. Specify relevant information from your store. (OPTIONAL) -->
<%

    ' Set store specific information so you can e.g. search and associate invoices with order numbers.
    ' -Order id 1, maybe the estore's order number/id?
    ' -Order id 2, could be an order number from another system?
    ' -User, Username, email or identifier for the user?
    Call kAPI.SetEstoreInfo("175012", "1999110234", "")

    ' If you don't have the order id available at this stage, you can later use the method updateOrderNo().

%>
<!-- 5. Set additional information. (OPTIONAL) -->
<%

    ' Comment?
    kAPI.SetComment("A text string stored in the invoice commentary area.")

    ' Shipment type?
    ' Normal shipment is defaulted, delays the start of invoice expiration/due-date.
    Call kAPI.SetShipmentInfo("delay_adjust", EXPRESS_SHIPMENT)

%>
<!-- 6. Invoke addTransaction and transmit the data. -->
<%

    On Error Resume Next

    ' Transmit all the specified data, from the steps above, to Klarna.
    ' -pno, Date of birth for DE.
    ' -gender, The customer is a male.
    ' -flags, No specific behaviour like RETURN_OCR or TEST_MODE.
    ' -pclass, -1, notes that this is an invoice purchase, for part payment purchase you will have a pclass object on which you use getId().
    ' -encoding, null to automatically use it for DE.
    Dim result
    result = kAPI.AddTransaction("410321-9202", null, NO_FLAG, PCLASS_INVOICE, null, true)

    If Err.number = 0 Then
        ' Success

        'Check the order status
        If result(1) = PENDING Then
            ' The order is under manual review and will be accepted or denied at a later stage.
            ' Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
            ' You should still show it to the customer as it was accepted, to avoid further attempts to fraud.
        End If

        ' Here we get the invoice number
        Dim invoiceNumber
        invoiceNumber = result(0)

        ' Order is complete, store it in a database.
        Response.Write("Invoice #" & invoiceNumber)
    Else
        ' Something went wrong
        Response.Write("Error occured: " & Err.number & " - " & Err.Description & "</br>" & Err.Source & "</br>")
    End If
%>
<!-- Finished -->
<%@page import="com.klarna.api.KlarnaCurrency"%>
<%@page import="com.klarna.api.pclasses.MySQLStorage"%>
<%@page import="com.klarna.api.flags.Status"%>
<%@page import="com.klarna.api.flags.PClass"%>
<%@page import="com.klarna.api.flags.Invoice"%>
<%@page import="com.klarna.api.flags.Gender"%>
<%@page import="com.klarna.api.flags.Shipment"%>
<%@page import="com.klarna.api.InformationType"%>
<%@page import="com.klarna.api.flags.Address"%>
<%@page import="java.util.EnumSet"%>
<%@page import="com.klarna.api.flags.Goods"%>
<%@page import="com.klarna.api.KlarnaCountry"%>
<%@page import="com.klarna.api.KlarnaAddr"%>
<%@page import="com.klarna.api.KlarnaPClass"%>
<%@page import="com.klarna.api.KlarnaConfig"%>
<%@page import="com.klarna.api.Klarna"%>
<%@page contentType="text/html" pageEncoding="ISO-8859-1"%>

<%

    /*
     *  1. Initialize and setup the Klarna instance.
     */
    Klarna k = new Klarna();

    /*
     *  Configure the Klarna object using the config() method. (Alternative 1)
     */

    /* KlarnaConfig conf = new KlarnaConfig();

    // Define values:
    conf.setEid(1);                         // Merchant ID or Estore ID, an Integer above 0.
    conf.setSecret("sharedSecret");         // The shared secret which accompanied your eid.
    conf.setCountry(KlarnaCountry.SE);      // The country of your store.
    conf.setLanguage(KlarnaLanguage.SV);    // The language of your store.
    conf.setCurrency(KlarnaCurrency.SEK);   // The currency of your store.
    conf.setMode(Klarna.BETA);              // or Klarna.LIVE when you are ready to go live.

    // Define pclass settings:
    conf.setPcStorage("json");              // Storage module. Currently only json is supported.
    conf.setPcURI("/srv/pclasses.json");    // Where the json file for the pclasses are stored.

    // Should we use SSL?
    conf.setSsl(false);

    // Should we error report/status report to klarna.
    conf.setCandice(true);                  // set to false if your server doesn't support UDP

    // Do we want to see normal debug information?
    conf.setDebug(null);                    // true to debug, null or false not to debug
    // Set the config object.
    k.config(conf);

     */


    /*
     *  Configure the Klarna object using the config() method (Alternative 2)
     */

    /*
     *   k.config(1,                     // e-store ID
     *           "sharedSecret",         // shared secret
     *           KlarnaCountry.SE,       // Country constant
     *           KlarnaLanguage.SV,      // Language constant
     *           KlarnaCurrency.SEK,     // Currency constant
     *           Klarna.BETA,            // Mode, BETA or LIVE
     *           "json",                 // Storage module
     *           "/srv/pclasses.json",   // Storage location
     *           true,                   // SSL
     *           true                    // Candice
     *           );
     *
     *  k.debug = false;
     */

    /*
     *  Configure the Klarna object using the config() method (Alternative 3)
     */

    k.config(KlarnaConfig.fromJson("klarna.json"));

    /*  the file would contain the following data to set the same information as above alternatives:
     * {
     *      "eid":1,
     *      "secret":"sharedSecret",
     *      "country":"SE",
     *      "language":"SV",
     *      "currency":"SEK",
     *      "mode":1,
     *      "ssl":false,
     *      "candice":true,
     *      "pcStorage":"json",
     *      "pcURI":"/srv/pclasses.json"
     *  }
     *
     */

    /*
     *  Configure with the constructor right away. Minimal constructor showed here. (Alternative 4)
     */
    // MySQLStorage mysql = new MySQLStorage("user", "password", "address", "dbname", "dbtable", 3306);
    // Klarna klarna = new Klarna(1, "sharedSecret", KlarnaCountry.SE, KlarnaCurrency.SEK, mysql, Klarna.BETA);


    /*
     *  2. Add the article(s), shipping and/or handling fee.
     */
    //  Here we add a normal product to our goods list.

    k.addArticle(1, // Quantity
            "MG200MMS", // Article number
            "Matrox G200 MMS", // Article name/title
            299.99, // Price
            19d, // 19% VAT. a double
            0d, // Discount, a double
            Goods.INC_VAT);   // Price is including VAT

    //Next we might want to add a shipment fee for the product
    EnumSet<Goods> goodsflags = EnumSet.of(Goods.INC_VAT, Goods.IS_SHIPMENT); // Some flags can be added together.
    k.addArticle(1,
            "123",
            "Shipping fee",
            4.5,
            19d,
            0d,
            goodsflags);   // Price is including VAT and is shipment fee

    k.addArticle(1,
            "1234",
            "Handling fee",
            1.5,
            19d,
            0d, // Flags can be added together in the method call aswell.
            Goods.INC_VAT.toInt() + Goods.IS_HANDLING.toInt());  // Price is including VAT and is handling/invoice fee


    /*
     * 3. Create and set the address(es).
     */

    //Create the address object and specify the values.
    KlarnaAddr addr = new KlarnaAddr(
            "always_accepted@klarna.com", // Email address
            "", // We skip the normal land line phone. only one is needed.
            "4676520000", // Mobile number
            "Testperson-se", // First (given) name
            "Approved", // Last (family) name
            "", // no care of ( c/o )
            "Stårgatan 1", // for DE and NL specify street number in houseNo
            "12345", // Zip code
            "Ankeborg", // City
            KlarnaCountry.SE, // KlarnaCountry constant
            null,
            null);

    //There are also set/get methods to do the same thing, like:
    addr.setEmail("always_accepted@klarna.com");

    // Next we tell the klarna instance to use the address in the next order.
    k.setAddress(Address.IS_BILLING, addr);     // Billing / invoice address
    k.setAddress(Address.IS_SHIPPING, addr);    // Shipping / delivery address

    /*
     *  4. Specify relevant information from your store. (OPTIONAL)
     */

    k.setEstoreInfo(
            "987654", // Maybe the estores order number/id
            "1234567890", // Could be an order number from another system?
            "" // Username, email or identifier for the user?
            );
    // another option is to omit the last field entirely.

    //If you don't have the order id available at this stage, you can later use the method updateOrderNo().

    /*
     *  5. Set additional informaion (OPTIONAL)
     */
    // A comment maybe?
    k.setComment("A text string stored in the invoice commentary area.");

    // Session IDs?
    /* If you've called this before the purchase, where the user enters his information,
    Klarna will be able to easier detect fraud or identify previous customer.
    Increasing your acceptance rate. */
    out.print(k.checkoutHTML());

    // Shipment type?
    k.setAdditionalInformation(InformationType.SHIPMENT, "delay_adjust", Shipment.EXPRESS_SHIPMENT);

    /* If a company is shopping, reference has to be set. */
    if (addr.isCompany()) {
        k.setReference("Reference Code");
    }


    /*
     *  6. Invoke addTransaction and transmit the data.
     */

    try {
        k.setClientIP(request.getRemoteAddr());
        EnumSet<Invoice> transactionflag = EnumSet.of(Invoice.NO_FLAG);
        String[] result = k.addTransaction("410321-9202", null,
                transactionflag,
                PClass.INVOICE.value());

        //Check the order status
        Status status = Status.getStatus(result[1]); // An example of how you could do it.
        if (status.equals(Status.PENDING)) {
            out.println(status.name()); // Outputs "PENDING".

            /* The order is under manual review and will be accepted or denied at a later stage.
            Use cronjob with checkOrderStatus() or visit Klarna Online to check to see if the status has changed.
            You should still show it to the customer as it was accepted, to avoid further attempts to fraud. */
        }
        //Here we get the invoice number
        String invNo = result[0];
        out.println(invNo);

        //Order is complete, store it in a database.
    } catch (Exception ex) {
        //The purchase was denied or something went wrong, print the message:
        out.println(ex.getMessage());
    }


%>
// ----------------------------------------------------------------------------
// <copyright file="AddTransactionExample.cs" company="Klarna AB">
//    Copyright 2013 Klarna AB
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// <author>Klarna Support: support@klarna.com</author>
// <link>http://integration.klarna.com/</link>
// ----------------------------------------------------------------------------
namespace KlarnaDotNetApi.Examples
{
    using System;
    using Klarna.Api;

    /// <summary>
    /// This is an example of how to use the AddTransaction call.
    /// </summary>
    public class AddTransactionExample : IExample
    {
        /// <summary>
        /// Method to run the example
        /// </summary>
        public void Run()
        {
            ////------------------------------------------------------------
            // 1. Initialize and setup the API instance.
            ////------------------------------------------------------------

            Configuration configuration = new Configuration(
                Country.Code.SE, Language.Code.SV, Currency.Code.SEK,
                Encoding.Sweden)
            {
                Eid = 0,
                Secret = "sharedsecret",
                IsLiveMode = false
            };

            Api api = new Api(configuration);
            api.PClassStorageUri = @"pclasses.xml";

            // It's important to set the end customers IP address
            api.ClientIp = "192.0.2.9";

            ////------------------------------------------------------------
            // 2. Add the article(s), shipping and/or handling fee.
            ////------------------------------------------------------------

            api.AddArticle(
                4, "1234e", "Matrox G200 MMS", 299.99, 25, 0,
                GoodsFlags.IncVAT);

            api.AddArticle(
                1, string.Empty, "Shipment fee", 20.0, 25, 0,
                GoodsFlags.Shipping | GoodsFlags.IncVAT);

            api.AddArticle(
                1, string.Empty, "Handling fee", 10.0, 25, 0,
                GoodsFlags.Handling | GoodsFlags.IncVAT);

            ////------------------------------------------------------------
            // 3. Create and set the address(es).
            ////------------------------------------------------------------

            api.ShippingAddress = new Address()
            {
                Email = "pending_approved@shipping.xxx",
                PhoneNumber = string.Empty,
                CellPhoneNumber = "0765260000",
                FirstName = "Testperson-se",
                LastName = "Approved",
                Street = "Stårgatan 1",
                CareOf = string.Empty,
                ZipCode = "12345",
                City = "Ankeborg",
                Country = Country.Code.SE,
                HouseNumber = string.Empty,
                HouseExtension = string.Empty,
                CompanyName = string.Empty
            };

            api.BillingAddress = new Address()
            {
                Email = "pending_approved@billing.xxx",
                PhoneNumber = string.Empty,
                CellPhoneNumber = "0765260000",
                FirstName = "Testperson-se",
                LastName = "Approved",
                Street = "Stårgatan 1",
                CareOf = string.Empty,
                ZipCode = "12345",
                City = "Ankeborg",
                Country = Country.Code.SE,
                HouseExtension = string.Empty,
                CompanyName = string.Empty
            };

            //------------------------------------------------------------
            // 4. Set additional information. (OPTIONAL)
            //------------------------------------------------------------
            api.Reference = "Reference";
            api.ReferenceCode = "Reference code";

            api.OrderId1 = "Order id 1";
            api.OrderId2 = "Order id 2";

            api.Comment = "A text string stored in the invoice commentary area.";

            // Normal shipment type is the default value
            api.ShipmentInfo["delay_adjust"] = ShipmentType.Express;

            ////------------------------------------------------------------
            // 5. Invoke AddTransaction and transmit the data.
            ////------------------------------------------------------------

            try
            {
                InvoiceResponse response = api.AddTransaction(
                    "410321-9202", Gender.Male, TransactionFlags.NoFlag);

                Console.WriteLine("Successfully created the invoice.");
                Console.WriteLine(string.Format(
                    "Number: {0}", response.InvoiceNumber));
                Console.WriteLine(string.Format(
                    "Order status: {0}", response.OrderStatus));
            }
            catch (KlarnaException ex)
            {
                Console.WriteLine("An error occurred during the call to Klarna");
                Console.WriteLine("Error code: {0}", ex.ErrorCode);
                Console.WriteLine("Error description: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "An exception occurred during the call to Klarna");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

Input data:

  Variable Type Description
Required pno/birthdate string Use the following format:

Sweden: yymmdd-nnnn, it can be sent with or without dash "-" or with or without the two first numbers in the year.
Finland: ddmmyy-nnnn
Denmark: ddmmyynnnn
Norway: ddmmyynnnnn
Germany: ddmmyyyy
Austria: ddmmyyyy
Netherlands: ddmmyyyy

d = day, m = month, y = year, n = person specific numbers

If it is a purchase with a company registration number, the reference person can be typed in the first and last name fields. If a social security number/birth date belongs to a person under 18 or if the social security number/birth date is invalid, Klarna will not make a credit report and will instead return an error status.
  gender integer The customer's gender (0=female, 1=male). Required for purchases in Germany and Netherlands.
  reference string The reference person for the purchase if it is a company purchase. You can also use this field to write a message or other important information to the customer on the invoice.
  reference_code string The reference code for the sale. You can also use this field to write a message or other important information to the customer on the invoice.
  orderid1 string Orderid
  orderid2 string Orderid
Required delivery_addr array The customer's address created by you using a call to the function setAddress.
Required billing_addr array The customer's address created by you using a call to the function setAddress.
Required clientIp string The IP-address from where the customer connects to the network.
Required flags integer A number of flags affecting the invoice purchase. Enter 0 to not designate a flag.

KRED_AUTO_ACTIVATE (value: 1)
Note: For this flag to work properly the online configuration for your store must be updated by Klarna.

If you designate this flag an invoice is created directly in the ’active’ state, i.e. Klarna will buy the invoice immediately.
When auto activation is used the invoice is created as both a .pdf and a .jpg file, available to you at https://online.klarna.com/invoices/"invoice number".jpg and .pdf. These invoices are automatically deleted after 30 days. Please note! If a ready_date (below) is specified the invoice will not be auto-activated until this date.

KRED_TEST_MODE (value: 2)

If you designate this flag an invoice is created in test mode, even if your store is fully operational. Recommended for testing without disrupting regular invoicing.

RETURN_OCR (value: 8192)

This will allow you to retrieve the ocr attached to the invoice.
Note that this will change the given response to an Array containing - [invno, ocr, invoiceStatus]
 
Required currency integer Currency code to be used for the invoices.

Swedish krona: KRED_SEK (value: 0)
Norwegian krona: KRED_NOK (value: 1)
Euro: KRED_EUR (value: 2)
Danish krona: KRED_DKK (value: 3)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required country integer Code for the country where your sales will be in:

Sweden: KRED_ISO3166_SE (value: 209)
Finland: KRED_ISO3166_FI (value: 73)
Denmark: KRED_ISO3166_DK (value: 59)
Norway: KRED_ISO3166_NO (value: 164)
Germany: KRED_ISO3166_DE (value: 81)
Austria: KRED_ISO3166_AT (value: 15)
Netherlands: KRED_ISO3166_NL (value: 154)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required language integer Language code for the language used on the invoice.


Swedish: KRED_ISO639_SV (value: 138)
Norwegian: KRED_ISO639_NB (value: 97)
Finnish : KRED_ISO639_FI (value: 37)
Danish: KRED_ISO639_DA (value: 27)
German: KRED_ISO639_DE (value: 28)
Austria: KRED_ISO639_DE (value: 28)
Dutch: KRED_ISO639_NL (value: 101)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required eid integer An e-store ID which refers to your store in Klarna's database
Required secret string A shared secret used to secure all traffic exchanged by Klarna and your store
Required pno_encoding integer Indicates the country where the person/customer is registered in:

Sweden: value: 2
Norway: value: 3
Finland: value: 4
Denmark: value: 5
Germany: value: 6
Austria: value: 8
Netherlands: value: 7

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required pclass integer This argument designates a campaign code to be used at the purchase and is utilized when the sale is a part payment or a special campaign purchase. If the sale is an invoice purchase this argument shall be set to -1.

-1 = invoice
xxx = campaign
xxx = all other pclasses*

Please note that part payment and special campaign purchases are not available for companies.

*There are two ways to retrieve pclasses.

1. Go to Klarna Online and press "view store" button in the menu on the left. In the store view, click "Click here to view campaigns".

2. Use the function fetch_pclasses to save all pclass values to your database.
Required goodsList array A list of items. Each item on the list is created by a call with the addArticle function. Tip: If you want to add a total discount, simply add another item titled “Discount” with a negative price value.
  comment string A text string stored in the invoice commentary area.
  estoreUser string The customers name in your store. Good to pass if you want to perform searches with it at Klarna Online
Required shipmentinfo array [delay_adjust] Required
  • (int) - The two values determine how long after invoice activation Klarna starts countdown to the expiration date. Both countdowns are by default zero days. The time of the countdowns can be negotiated with Klarna.

    KRED_NORMAL_SHIPMENT (value: 1) KRED_EXPRESS_SHIPMENT (value: 2).
     
  travel_info array Not used at this moment
  income_expense array [yearly_salary]
  • (int) - Customer's yearly salary. This was once required in Denmark.
    Since March 2012 we no longer require this information, it can be left empty and does not need to be supplied at all.
     
  bank_info array Not used at this moment
  session_id array [dev_id_1]
  • (string) -
     
[dev_id_2]
  • (string) -
     
[dev_id_3]
  • (string) -
     
[beh_id_1]
  • (string) -
     
[beh_id_2]


     
[beh_id_3]
  • (string) -
  extra_info array [cust_no]
  • (string) - The customer number in the estores system
     
[ready_date]
  • (string) - A date in the format YYYY-MM-DD describing when the invoice items are ready for delivery. Please note that if the KRED_AUTO_ACTIVATE flag (value: 1) is set the invoice will not be activated until the date set in ready_date.
     
[pin]
  • (string) - If you are using Klarna Mobil you send the customers pin code here. Otherwise you only use an empty string.

 

deleteInvoice

Purpose:

The deleteInvoice function is used to delete a passive invoice.

Return value:

String - OK 

or

Throws an exception with error code and error message.

<?php

require_once dirname(dirname(__FILE__)) . '/Klarna.php';

// Dependencies from http://phpxmlrpc.sourceforge.net/
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc';

/**
 * 1. Initialize and setup the Klarna instance.
 */

$k = new Klarna();

$k->config(
    123456,               // Merchant ID
    'sharedSecret',       // Shared Secret
    KlarnaCountry::SE,    // Country
    KlarnaLanguage::SV,   // Language
    KlarnaCurrency::SEK,  // Currency
    Klarna::BETA,         // Server
    'json',               // PClass Storage
    '/srv/pclasses.json', // PClass Storage URI path
    true,                 // SSL
    true                  // Remote logging of response times of xmlrpc calls
);

// OR you can set the config to loads from a file, for example /srv/klarna.json:
// $k->setConfig(new KlarnaConfig('/srv/klarna.json'));

/**
 * 2. Remove the invoice
 */

//Here you enter the invoice number you got from addTransaction():
$invNo = '123456';

try {
    $result = $k->deleteInvoice($invNo);

    echo "Result: {$result}\n";

    //Invoice removed, proceed accordingly.
} catch(Exception $e) {
    //Something went wrong or the invoice doesn't exist.
    echo "{$e->getMessage()} (#{$e->getCode()})\n";
}
<%
    Option Explicit
%>
<!-- Please note that the include below points to the web root -->
<!-- The include has to be modified if example is placed elsewhere -->
<!-- #include virtual="Klarna.asp" -->
<!-- 1. Initialize and setup the Klarna instance -->
<%

    ' Grab the API object
    ' -Merchant ID or Estore ID, an integer above 0.
    ' -The shared secret which accompanied your eid.
    ' -Country, language and currency.
    Dim kAPI
    Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")

    ' Do we want to see normal debug information?
    kAPI.DebugInformation = True

    ' Set the address and port to Klarna server.
    ' Use LIVE or BETA depending on which server your eid is associated with.
    kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
    kAPI.SetHost(BETA_HOST) ' or LIVE_HOST

    ' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
    kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))

%>
<!-- 2. Delete the invoice -->
<%

    On Error Resume Next

    ' Here you enter the invoice number you got from addTransaction():
    Dim invoiceNumber
    invoiceNumber = CStr(Request.QueryString("invno"))

    kAPI.DeleteInvoice(invoiceNumber)

    If Err.number = 0 Then
        ' Success
    
        ' Invoice removed, proceed accordingly.
        Response.Write("<br>Invoice "& invoiceNumber & " was succesfully removed<br/>")
    Else 
        ' Something went wrong
        Response.Write("Error occured: " & Err.number & " - " & Err.Description & "</br>" & Err.Source & "</br>")
    End If

%>
<!-- Finished -->
<%@page import="com.klarna.api.KlarnaCalc"%>
<%@page import="com.klarna.api.KlarnaCountry"%>
<%@page import="com.klarna.api.KlarnaAddr"%>
<%@page import="com.klarna.api.KlarnaPClass"%>
<%@page import="com.klarna.api.KlarnaConfig"%>
<%@page import="com.klarna.api.Klarna"%>
<%@page contentType="text/html" pageEncoding="ISO-8859-1"%>

<%

    /*
     *  1. Initialize and setup the Klarna instance.
     */
    Klarna k = new Klarna();

    /*
     *  Configure the Klarna object using the config() method. (Alternative 1)
     */

    /* KlarnaConfig conf = new KlarnaConfig();

    // Define values:
    conf.setEid(1);                         // Merchant ID or Estore ID, an Integer above 0.
    conf.setSecret("sharedSecret");         // The shared secret which accompanied your eid.
    conf.setCountry(KlarnaCountry.SE);      // The country of your store.
    conf.setLanguage(KlarnaLanguage.SV);    // The language of your store.
    conf.setCurrency(KlarnaCurrency.SEK);   // The currency of your store.
    conf.setMode(Klarna.BETA);              // or Klarna.LIVE when you are ready to go live.

    // Define pclass settings:
    conf.setPcStorage("json");              // Storage module. Currently only json is supported.
    conf.setPcURI("/srv/pclasses.json");    // Where the json file for the pclasses are stored.

    // Should we use SSL?
    conf.setSsl(false);

    // Should we error report/status report to klarna.
    conf.setCandice(true);                  // set to false if your server doesn't support UDP

    // Do we want to see normal debug information?
    conf.setDebug(null);                    // true to debug, null or false not to debug
    // Set the config object.
    k.config(conf);

     */


    /*
     *  Configure the Klarna object using the config() method (Alternative 2)
     */

    /*
     *   k.config(1,                     // e-store ID
     *           "sharedSecret",         // shared secret
     *           KlarnaCountry.SE,       // Country constant
     *           KlarnaLanguage.SV,      // Language constant
     *           KlarnaCurrency.SEK,     // Currency constant
     *           Klarna.BETA,            // Mode, BETA or LIVE
     *           "json",                 // Storage module
     *           "/srv/pclasses.json",   // Storage location
     *           true,                   // SSL
     *           true                    // Candice
     *           );
     *
     *  k.debug = false;
     */

    /*
     *  Configure the Klarna object using the config() method (Alternative 3)
     */

    k.config(KlarnaConfig.fromJson("klarna.json"));

    /*  the file would contain the following data to set the same information as above alternatives:
     * {
     *      "eid":1,
     *      "secret":"sharedSecret",
     *      "country":"SE",
     *      "language":"SV",
     *      "currency":"SEK",
     *      "mode":1,
     *      "ssl":false,
     *      "candice":true,
     *      "pcStorage":"json",
     *      "pcURI":"/srv/pclasses.json"
     *  }
     *
     */

    /*
     *  Configure with the constructor right away. Minimal constructor showed here.
     */
    // MySQLStorage mysql = new MySQLStorage("user", "password", "address", "dbname", "dbtable", 3306);
    // Klarna klarna = new Klarna(1, "sharedSecret", KlarnaCountry.SE, KlarnaCurrency.SEK, mysql, Klarna.BETA);

    /**
     * 2. Remove the invoice
     */
    // Here you enter the invoice number you got from addTransaction();
    String invNo = request.getParameter("invoice_number");

    try {
        k.deleteInvoice(invNo);

        // Invoice removed, proceed accordingly.

    } catch (Exception e) {
        // Something went wrong, print the message.
        out.println(e.getMessage());
    }
%>
// ----------------------------------------------------------------------------
// <copyright file="DeleteInvoiceExample.cs" company="Klarna AB">
//    Copyright 2013 Klarna AB
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// <author>Klarna Support: support@klarna.com</author>
// <link>http://integration.klarna.com/</link>
// ----------------------------------------------------------------------------
namespace KlarnaDotNetApi.Examples
{
    using System;
    using Klarna.Api;

    /// <summary>
    /// This is an example of how to use the DeleteInvoice call.
    /// </summary>
    public class DeleteInvoiceExample : IExample
    {
        /// <summary>
        /// Method to run the example
        /// </summary>
        public void Run()
        {
            ////------------------------------------------------------------
            // 1. Initialize and setup the API instance.
            ////------------------------------------------------------------

            Configuration configuration = new Configuration(
                Country.Code.SE, Language.Code.SV, Currency.Code.SEK,
                Encoding.Sweden)
            {
                Eid = 0,
                Secret = "sharedsecret",
                IsLiveMode = false
            };

            Api api = new Api(configuration);
            api.PClassStorageUri = @"pclasses.xml";

            // It's important to set the end customers IP address
            api.ClientIp = "192.0.2.9";

            ////------------------------------------------------------------
            // 2. Delete the invoice.
            ////------------------------------------------------------------

            Console.WriteLine("Please enter invoice number and press Enter");
            string invoiceNumber = Console.ReadLine();

            try
            {
                Console.WriteLine(
                    "Trying to delete invoice number: {0}", invoiceNumber);
                if (api.DeleteInvoice(invoiceNumber))
                {
                    Console.WriteLine("Successfully deleted the invoice.");
                }
                else
                {
                    Console.WriteLine("Failed to delete the invoice.");
                }
            }
            catch (KlarnaException ex)
            {
                Console.WriteLine("An error occurred during the call to Klarna");
                Console.WriteLine("Error code: {0}", ex.ErrorCode);
                Console.WriteLine("Error description: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "An exception occurred during the call to Klarna");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

Input data:

  Variable Type Description
Required eid integer An store ID which refers to your store in Klarna's database.
Required invno string The passive invoice number
Required secret string A shared secret used to secure all traffic exchanged by Klarna and your store

 

activateInvoice

Purpose:

The activateInvoice function is used to activate a passive invoice. Please note that this function call cannot activate an invoice created in test mode. It is however possible to manually activate that type of invoices.

Return value:

String - A URL pointing to a PDF version of the activated invoice. 
The URL is valid for 30 days. 

or

Throws an exception with error code and error message.

<?php

require_once dirname(dirname(__FILE__)) . '/Klarna.php';

// Dependencies from http://phpxmlrpc.sourceforge.net/
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc';

/**
 * 1. Initialize and setup the Klarna instance.
 */

$k = new Klarna();

$k->config(
    123456,               // Merchant ID
    'sharedSecret',       // Shared Secret
    KlarnaCountry::SE,    // Country
    KlarnaLanguage::SV,   // Language
    KlarnaCurrency::SEK,  // Currency
    Klarna::BETA,         // Server
    'json',               // PClass Storage
    '/srv/pclasses.json', // PClass Storage URI path
    true,                 // SSL
    true                  // Remote logging of response times of xmlrpc calls
);

// OR you can set the config to loads from a file, for example /srv/klarna.json:
// $k->setConfig(new KlarnaConfig('/srv/klarna.json'));


/**
 * 2. Activate the invoice
 */

// Here you enter the invoice number you got from addTransaction():
$invNo = '123456';

try {
    // You can specify a new pclass ID if the customer wanted to change it
    // before you activate.
    $url = $k->activateInvoice($invNo, $pclass = KlarnaPClass::INVOICE);

    echo "{$url}\n";

    // The url points to a PDF file for the invoice.
    // Invoice activated, proceed accordingly.
} catch(Exception $e) {
    // Something went wrong or the invoice doesn't exist.
    echo "{$e->getMessage()} (#{$e->getCode()})\n";
}
<%
    Option Explicit
%>
<!-- Please note that the include below points to the web root -->
<!-- The include has to be modified if example is placed elsewhere -->
<!-- #include virtual="Klarna.asp" -->
<!-- 1. Initialize and setup the Klarna instance -->
<%

    ' Grab the API object
    ' -Merchant ID or Estore ID, an integer above 0.
    ' -The shared secret which accompanied your eid.
    ' -Country, language and currency.
    Dim kAPI
    Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")

    ' Do we want to see normal debug information?
    kAPI.DebugInformation = True

    ' Set the address and port to Klarna server.
    ' Use LIVE or BETA depending on which server your eid is associated with.
    kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
    kAPI.SetHost(BETA_HOST) ' or LIVE_HOST

    ' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
    kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))

%>
<!-- 2. Activate the invoice -->
<%

    On Error Resume Next

    ' Here you enter the invoice number you got from addTransaction():
    Dim invoiceNumber
    invoiceNumber = CStr(Request.QueryString("invno"))

    ' You can specify a new pclass ID if the customer wanted to change it before you activate.
    Dim url
    url = kAPI.ActivateInvoice(invoiceNumber, PCLASS_INVOICE, True)

    If Err.number = 0 Then
        ' Success
        Response.Write("The returned url is: " & url)
        Response.Write("<br><a href=" & url & ">Link to invoice</a>")
    Else 
        ' Something went wrong
        Response.Write("Error occured: " & Err.number & " - " & Err.Description & "</br>" & Err.Source & "</br>")
    End If

%>
<!-- Finished -->
<%@page import="com.klarna.api.pclasses.MySQLStorage"%>
<%@page import="com.klarna.api.KlarnaPClass"%>
<%@page import="com.klarna.api.KlarnaLanguage"%>
<%@page import="com.klarna.api.KlarnaCountry"%>
<%@page import="com.klarna.api.KlarnaCurrency"%>
<%@page import="com.klarna.api.KlarnaConfig"%>
<%@page import="com.klarna.api.Klarna"%>
<%@page contentType="text/html" pageEncoding="ISO-8859-1"%>

<%

    /*
     *  1. Initialize and setup the Klarna instance.
     */
    Klarna k = new Klarna();

    /*
     *  Configure the Klarna object using the config() method. (Alternative 1)
     */

    /* KlarnaConfig conf = new KlarnaConfig();

    // Define values:
    conf.setEid(1);                         // Merchant ID or Estore ID, an Integer above 0.
    conf.setSecret("sharedSecret");         // The shared secret which accompanied your eid.
    conf.setCountry(KlarnaCountry.SE);      // The country of your store.
    conf.setLanguage(KlarnaLanguage.SV);    // The language of your store.
    conf.setCurrency(KlarnaCurrency.SEK);   // The currency of your store.
    conf.setMode(Klarna.BETA);              // or Klarna.LIVE when you are ready to go live.

    // Define pclass settings:
    conf.setPcStorage("json");              // Storage module. Currently only json is supported.
    conf.setPcURI("/srv/pclasses.json");    // Where the json file for the pclasses are stored.

    // Should we use SSL?
    conf.setSsl(false);

    // Should we error report/status report to klarna.
    conf.setCandice(true);                  // set to false if your server doesn't support UDP

    // Do we want to see normal debug information?
    conf.setDebug(null);                    // true to debug, null or false not to debug
    // Set the config object.
    k.config(conf);

     */


    /*
     *  Configure the Klarna object using the config() method (Alternative 2)
     */

    /*
     *   k.config(1,                     // e-store ID
     *           "sharedSecret",         // shared secret
     *           KlarnaCountry.SE,       // Country constant
     *           KlarnaLanguage.SV,      // Language constant
     *           KlarnaCurrency.SEK,     // Currency constant
     *           Klarna.BETA,            // Mode, BETA or LIVE
     *           "json",                 // Storage module
     *           "/srv/pclasses.json",   // Storage location
     *           true,                   // SSL
     *           true                    // Candice
     *           );
     *
     *  k.debug = false;
     */

    /*
     *  Configure the Klarna object using the config() method (Alternative 3)
     */

    k.config(KlarnaConfig.fromJson("klarna.json"));

    /*  the file would contain the following data to set the same information as above alternatives:
     * {
     *      "eid":1,
     *      "secret":"sharedSecret",
     *      "country":"SE",
     *      "language":"SV",
     *      "currency":"SEK",
     *      "mode":1,
     *      "ssl":false,
     *      "candice":true,
     *      "pcStorage":"json",
     *      "pcURI":"/srv/pclasses.json"
     *  }
     *
     */

    /*
     *  Configure with the constructor right away. Minimal constructor showed here.
     */
    MySQLStorage mysql = new MySQLStorage("user", "password", "address", "dbname", "dbtable", 3306);
    Klarna klarna = new Klarna(1, "sharedSecret", KlarnaCountry.SE, KlarnaCurrency.SEK, mysql, Klarna.BETA);

    /*
     *  2. Activate the invoice
     */

    // here you enter the invoice number you got from addTransaction:
    String invNo = request.getParameter("invoice_number");

    try {
        // If you used delay_adjust = express shipment, then you should set that before activating also.

        // You can specify a new pclass ID if the customer wanted to change it before you activate.
        // You can use:
        // k.activateInvoice(invNo, pclass-id);
        // k.activateInvoice(invNo, pclass-id, clear)
        String url = k.activateInvoice(invNo, KlarnaPClass.INVOICE);


        //The url points to a PDF file for the invoice.
        //Invoice activated, proceed accordingly.
    } catch (Exception e) {
        //Something went wrong or the invoice doesn't exist.
        out.println("Error: " + e.getMessage());
    }

%>
// ----------------------------------------------------------------------------
// <copyright file="ActivateInvoiceExample.cs" company="Klarna AB">
//    Copyright 2013 Klarna AB
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// <author>Klarna Support: support@klarna.com</author>
// <link>http://integration.klarna.com/</link>
// ----------------------------------------------------------------------------
namespace KlarnaDotNetApi.Examples
{
    using System;
    using Klarna.Api;

    /// <summary>
    /// This is an example of how to use the ActivateInvoice call.
    /// </summary>
    public class ActivateInvoiceExample : IExample
    {
        /// <summary>
        /// Method to run the example
        /// </summary>
        public void Run()
        {
            ////------------------------------------------------------------
            // 1. Initialize and setup the API instance.
            ////------------------------------------------------------------

            Configuration configuration = new Configuration(
                Country.Code.SE, Language.Code.SV, Currency.Code.SEK, 
                Encoding.Sweden)
            {
                Eid = 0,
                Secret = "sharedsecret",
                IsLiveMode = false
            };

            Api api = new Api(configuration);
            api.PClassStorageUri = @"pclasses.xml";

            // It's important to set the end customers IP address
            api.ClientIp = "192.0.2.9";

            ////------------------------------------------------------------
            // 2. Activate the invoice.
            ////------------------------------------------------------------

            Console.WriteLine("Please enter invoice number and press Enter");
            string invoiceNumber = Console.ReadLine();

            try
            {
                string url = api.ActivateInvoice(invoiceNumber);
                Console.WriteLine("Successfully activated the invoice.");
                Console.WriteLine("Url: {0}", url);
            }
            catch (KlarnaException ex)
            {
                Console.WriteLine("An error occurred during the call to Klarna");
                Console.WriteLine("Error code: {0}", ex.ErrorCode);
                Console.WriteLine("Error description: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "An exception occurred during the call to Klarna");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

Input data:

  Variable Type Description
Required eid integer An e-store ID which refers to your store in Klarna's database.
Required invno string The passive invoice number.
Required secret string A shared secret used to secure all traffic exchanged by Klarna and your store.
Required pclass integer This argument designates a campaign code to be used at the purchase and is utilized when the sale is a part payment or a special campaign purchase. If the sale is an invoice purchase this argument shall be set to -1.

-1 = invoice
xxx = campaign
xxx = all other pclasses*

Please note that part payment and special campaign purchases are not available for companies.

*There are two ways to retrieve pclasses.

1. Go to Klarna Online and press "view store" button in the menu on the left. In the store view, click "Click here to view campaigns".

2. Use the function fetch_pclasses to save all pclass values to your database.
  shipment_info array [delay_adjust]
  • (int) - Determines how long after invoice activation Klarna starts countdown to the expiration date. Both values are by default 0. The terms of these parameters can be negotiated with Klarna.

    KRED_NORMAL_SHIPMENT (value: 1) KRED_EXPRESS_SHIPMENT (value: 2).
     

 

activatePart

Purpose:

The activatePart function is used to partially activate a passive invoice.

Explanation:

When partially activating an invoice, only the articles and quantities specified by you will be activated. For items which were not activated, a new passive invoice is created with a new invoice number.

Return value:

Struct - [url, invno]
The value of ”url” is a URL pointing to a temporary PDF-version of the activated invoice.
The value of ”invno” is the number on the new passive invoice. If the invoice is fully activated the struct will only contain the url.
The URL is valid for 30 days. 

or

Throws an exception with error code and error message.

<?php

require_once dirname(dirname(__FILE__)) . '/Klarna.php';

// Dependencies from http://phpxmlrpc.sourceforge.net/
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc';

/**
 * 1. Initialize and setup the Klarna instance.
 */

$k = new Klarna();

$k->config(
    123456,               // Merchant ID
    'sharedSecret',       // Shared Secret
    KlarnaCountry::SE,    // Country
    KlarnaLanguage::SV,   // Language
    KlarnaCurrency::SEK,  // Currency
    Klarna::BETA,         // Server
    'json',               // PClass Storage
    '/srv/pclasses.json', // PClass Storage URI path
    true,                 // SSL
    true                  // Remote logging of response times of xmlrpc calls
);

// OR you can set the config to loads from a file, for example /srv/klarna.json:
// $k->setConfig(new KlarnaConfig('/srv/klarna.json'));

/**
 * 2. Partially activate the invoice
 */

// Here you specify the quantity of an article you wish to partially activate.
// artNo must be the same as the one you used in addArticle() when you made the
// addTransaction() call.
$k->addArtNo(
    1,          // Quantity
    'MG200MMS'  // Article number
);

// Here you enter the invoice number you got from addTransaction():
$invNo = '123456';

try {
    $result = $k->activatePart(
        $invNo,               // Invoice number
        KlarnaPClass::INVOICE // Or the PClass ID used to make the order.
    );
    $url = $result['url'];
    echo "url: ${url}\n";
    if (isset($result['invno'])) {
        $invno = $result['invno'];
        echo "invno: ${invno}\n";
    }
    // The url points to a PDF file for the invoice.
    // The invno field is only present if the invoice was not entirely activated,
    // and in that case it contains the new invoice number.

    // Invoice activated, proceed accordingly.
} catch(Exception $e) {
    // Something went wrong or the invoice doesn't exist.
    echo "{$e->getMessage()} (#{$e->getCode()})\n";
}
<%
    Option Explicit
%>
<!-- Please note that the include below points to the web root -->
<!-- The include has to be modified if example is placed elsewhere -->
<!-- #include virtual="Klarna.asp" -->
<!-- 1. Initialize and setup the Klarna instance -->
<%

    ' Grab the API object
    ' -Merchant ID or Estore ID, an integer above 0.
    ' -The shared secret which accompanied your eid.
    ' -Country, language and currency.
    Dim kAPI
    Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")

    ' Do we want to see normal debug information?
    kAPI.DebugInformation = True

    ' Set the address and port to Klarna server.
    ' Use LIVE or BETA depending on which server your eid is associated with.
    kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
    kAPI.SetHost(BETA_HOST) ' or LIVE_HOST

    ' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
    kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))

%>
<!-- 2. Partially activate the invoice -->
<%

    On Error Resume Next

    ' Here you specify the quantity of an article you wish to partially activate.
    ' -Quantity
    ' -Article number, must be the same as the one you used in addArticle() when you made the addTransaction call.
    Call kAPI.AddArticleNumber(1, "MG200MMS")

    ' Here you enter the invoice number you got from addTransaction():
    Dim invoiceNumber
    invoiceNumber = CStr(Request.QueryString("invno"))

    ' You can specify a new pclass ID if the customer wanted to change it before you activate.
    Dim result
    Set result = kAPI.ActivatePart(invoiceNumber, PCLASS_INVOICE, True)

    If Err.number = 0 Then
        ' Success

        ' The url points to a PDF file for the invoice.
        Dim url
        url = result("url")

        Response.Write("The returned url is: " & url)
        Response.Write("<br/><a href=" & url & ">Link to invoice</a><br/>")

        ' If no invno key exist the entire invoice was activated, else it's the new
        ' invoice number
        If result.Exists("invno") = True Then
            Dim number
            number = result("invno")
            Response.Write("Invoice #" & number & "<br/>")
        else
            Response.Write("Invoice completly activated" & "<br/>")
        end if
    Else 
        ' Something went wrong
        Response.Write("Error occured: " & Err.number & " - " & Err.Description & "</br>" & Err.Source & "</br>")
    End If

%>
<!-- Finished -->
<%@page import="com.klarna.api.KlarnaCurrency"%>
<%@page import="com.klarna.api.KlarnaLanguage"%>
<%@page import="com.klarna.api.KlarnaCountry"%>
<%@page import="com.klarna.api.KlarnaPClass"%>
<%@page import="com.klarna.api.KlarnaConfig"%>
<%@page import="com.klarna.api.Klarna"%>
<%@page contentType="text/html" pageEncoding="ISO-8859-1"%>

<%

    /*
     *  1. Initialize and setup the Klarna instance.
     */
    Klarna k = new Klarna();

    /*
     *  Configure the Klarna object using the config() method. (Alternative 1)
     */

    /* KlarnaConfig conf = new KlarnaConfig();

    // Define values:
    conf.setEid(1);                         // Merchant ID or Estore ID, an Integer above 0.
    conf.setSecret("sharedSecret");         // The shared secret which accompanied your eid.
    conf.setCountry(KlarnaCountry.SE);      // The country of your store.
    conf.setLanguage(KlarnaLanguage.SV);    // The language of your store.
    conf.setCurrency(KlarnaCurrency.SEK);   // The currency of your store.
    conf.setMode(Klarna.BETA);              // or Klarna.LIVE when you are ready to go live.

    // Define pclass settings:
    conf.setPcStorage("json");              // Storage module. Currently only json is supported.
    conf.setPcURI("/srv/pclasses.json");    // Where the json file for the pclasses are stored.

    // Should we use SSL?
    conf.setSsl(false);

    // Should we error report/status report to klarna.
    conf.setCandice(true);                  // set to false if your server doesn't support UDP

    // Do we want to see normal debug information?
    conf.setDebug(null);                    // true to debug, null or false not to debug
    // Set the config object.
    k.config(conf);

     */


    /*
     *  Configure the Klarna object using the config() method (Alternative 2)
     */

    /*
     *   k.config(1,                     // e-store ID
     *           "sharedSecret",         // shared secret
     *           KlarnaCountry.SE,       // Country constant
     *           KlarnaLanguage.SV,      // Language constant
     *           KlarnaCurrency.SEK,     // Currency constant
     *           Klarna.BETA,            // Mode, BETA or LIVE
     *           "json",                 // Storage module
     *           "/srv/pclasses.json",   // Storage location
     *           true,                   // SSL
     *           true                    // Candice
     *           );
     *
     *  k.debug = false;
     */

    /*
     *  Configure the Klarna object using the config() method (Alternative 3)
     */

    k.config(KlarnaConfig.fromJson("klarna.json"));

    /*  the file would contain the following data to set the same information as above alternatives:
     * {
     *      "eid":1,
     *      "secret":"sharedSecret",
     *      "country":"SE",
     *      "language":"SV",
     *      "currency":"SEK",
     *      "mode":1,
     *      "ssl":false,
     *      "candice":true,
     *      "pcStorage":"json",
     *      "pcURI":"/srv/pclasses.json"
     *  }
     *
     */

    /*
     *  Configure with the constructor right away. Minimal constructor showed here.
     */
    // MySQLStorage mysql = new MySQLStorage("user", "password", "address", "dbname", "dbtable", 3306);
    // Klarna klarna = new Klarna(1, "sharedSecret", KlarnaCountry.SE, KlarnaCurrency.SEK, mysql, Klarna.BETA);

    /*
     *  2. Partially activate the invoice
     */

    // Here you specify the quantity of an article you wish to partially activate
    k.addArtNo(1, "MG200MMS"); // the article number must be the same as the one used in addArticle() when you made the addTransaction() or reserveAmount call.

    // Here you enter the invoice number you got from addTransaction();
    String invNo = request.getParameter("invoice_number");

    try {
        // If you used delay_adjust = express shipment, then you should set that before activating also.
        String[] result = k.activatePart(invNo, KlarnaPClass.INVOICE);

        String url = result[0];
        invNo = result[1];
        //The url points to a PDF file for the invoice.
        //The invno is 0 if the entire invoice was activated, or the new invoice number.
        //Invoice activated, proceed accordingly.
    } catch (Exception e) {
        //Something went wrong or the invoice doesn't exist.
        out.println("Error: " + e.getMessage());
    }

%>
// ----------------------------------------------------------------------------
// <copyright file="ActivatePartExample.cs" company="Klarna AB">
//    Copyright 2013 Klarna AB
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// <author>Klarna Support: support@klarna.com</author>
// <link>http://integration.klarna.com/</link>
// ----------------------------------------------------------------------------
namespace KlarnaDotNetApi.Examples
{
    using System;
    using Klarna.Api;

    /// <summary>
    /// This is an example of how to use the ActivatePart call.
    /// </summary>
    public class ActivatePartExample : IExample
    {
        /// <summary>
        /// Method to run the example
        /// </summary>
        public void Run()
        {
            ////------------------------------------------------------------
            // 1. Initialize and setup the API instance.
            ////------------------------------------------------------------

            Configuration configuration = new Configuration(
                Country.Code.SE, Language.Code.SV, Currency.Code.SEK,
                Encoding.Sweden)
            {
                Eid = 0,
                Secret = "sharedsecret",
                IsLiveMode = false
            };

            Api api = new Api(configuration);
            api.PClassStorageUri = @"pclasses.xml";

            // It's important to set the end customers IP address
            api.ClientIp = "192.0.2.9";

            ////------------------------------------------------------------
            // 2. Partially activate the invoice.
            ////------------------------------------------------------------

            Console.WriteLine("Please enter invoice number and press Enter");
            string invoiceNumber = Console.ReadLine();

            try
            {
                api.AddArticleNumber(2, "1234e");

                ActivatePartResponse response = api.ActivatePart(invoiceNumber);
                Console.WriteLine("Successfully activated parts of the invoice.");
                Console.WriteLine("Url: {0}", response.Url);
                Console.WriteLine(
                    "New invoice number: {0}", response.InvoiceNumber);
            }
            catch (KlarnaException ex)
            {
                Console.WriteLine("An error occurred during the call to Klarna");
                Console.WriteLine("Error code: {0}", ex.ErrorCode);
                Console.WriteLine("Error description: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "An exception occurred during the call to Klarna");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

Input data:

  Variable Type Description
Required eid integer An e-store ID which refers to your store in Klarna's database.
Required invno string The passive invoice number
Required artnos array A list of pairs containing quantity and article number. Each element in the list is created using a call to the addArtNo function.
Required secret string A shared secret used to secure all traffic exchanged by Klarna and your store
Required pclass integer This argument designates a campaign code to be used at the purchase and is utilized when the sale is a part payment or a special campaign purchase. If the sale is an invoice purchase this argument shall be set to -1.

-1 = invoice
xxx = campaign
xxx = all other pclasses*

Please note that part payment and special campaign purchases are not available for companies.

*There are two ways to retrieve pclasses.

1. Go to Klarna Online and press "view store" button in the menu on the left. In the store view, click "Click here to view campaigns".

2. Use the function fetch_pclasses to save all pclass values to your database.
Required shipment_info array [delay_adjust] Required
  • (int) - Determines how long after invoice activation Klarna starts countdown to the expiration date. Both values are by default 0. The terms of these parameters can be negotiated with Klarna.

    KRED_NORMAL_SHIPMENT (value: 1)  KRED_EXPRESS_SHIPMENT (value: 2).
     

 

Advanced Integration

activateReservation

Purpose:

The activateReservation function is used to activate purchases which have been previously reserved with the reserveAmount function.

Return value:

Array - [risk_status,invoice number]
The risk status can be either OK or no_risk.
The invoice can be downloaded from https://online.klarna.com/invoices/"invoice number".pdf or jpg 
The URL is valid for 30 days. 

or

Throws an exception with error code and error message.

<?php

require_once dirname(dirname(__FILE__)) . '/Klarna.php';

// Dependencies from http://phpxmlrpc.sourceforge.net/
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
require_once dirname(dirname(__FILE__)) .
    '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc';

/**
 * 1. Initialize and setup the Klarna instance.
 */
$k = new Klarna();
$k->config(
    123456,               // Merchant ID
    'sharedSecret',       // Shared Secret
    KlarnaCountry::SE,    // Country
    KlarnaLanguage::SV,   // Language
    KlarnaCurrency::SEK,  // Currency
    Klarna::BETA,         // Server
    'json',               // PClass Storage
    '/srv/pclasses.json', // PClass Storage URI path
    true,                 // SSL
    true                  // Remote logging of response times of xmlrpc calls
);

// OR you can set the config to loads from a file, for example /srv/klarna.json:
// $k->setConfig(new KlarnaConfig('/srv/klarna.json'));

/**
 * 2. Add the article(s), shipping and/or handling fee.
 */

// Here we add a normal product to our goods list.
$k->addArticle(
    4,                      // Quantity
    "MG200MMS",             // Article number
    "Matrox G200 MMS",      // Article name/title
    299.99,                 // Price
    25,                     // 25% VAT
    0,                      // Discount
    KlarnaFlags::INC_VAT    // Price is including VAT.
);

// Next we might want to add a shipment fee for the product
$k->addArticle(
    1,
    "",
    "Shipping fee",
    14.5,
    25,
    0,
    // Price is including VAT and is shipment fee
    KlarnaFlags::INC_VAT | KlarnaFlags::IS_SHIPMENT
);

// Lastly, we want to use an invoice/handling fee as well
$k->addArticle(
    1,
    "",
    "Handling fee",
    11.5,
    25,
    0,
    // Price is including VAT and is handling/invoice fee
    KlarnaFlags::INC_VAT | KlarnaFlags::IS_HANDLING
);

/**
 * 3. Create and set the address(es).
 */

// Create the address object and specify the values.
$addr = new KlarnaAddr(
    'always_approved@klarna.com', // email
    '',                           // Telno, only one phone number is needed.
    '0762560000',                 // Cellno
    'Testperson-se',              // Firstname
    'Approved',                   // Lastname
    '',                           // No care of, C/O.
    'Stårgatan 1',                // Street
    '12345',                      // Zip Code
    'Ankeborg',                   // City
    KlarnaCountry::SE,            // Country
    null,                         // HouseNo for German and Dutch customers.
    null                          // House Extension. Dutch customers only.
);

$k->setAddress(KlarnaFlags::IS_BILLING, $addr);
$k->setAddress(KlarnaFlags::IS_SHIPPING, $addr); // Shipping / delivery address

/**
 * 4. Specify relevant information from your store. (OPTIONAL)
 */

// Set store specific information so you can e.g. search and associate invoices
// with order numbers.
$k->setEstoreInfo(
    'order id #1',
    'order id #2'
);

// If you don't have the order id available at this stage, you can later use the
// method updateOrderNo().

/**
 * 5. Set additional information. (OPTIONAL)
 */

/** Comment **/

$k->setComment('A text string stored in the invoice commentary area.');

/** Extra info **/

// Normal shipment is defaulted, delays the start of invoice
// expiration/due-date.

$k->setShipmentInfo('key', 'value');
$k->setTravelInfo('key', 'value');
$k->setBankInfo('key', 'value');
$k->setIncomeInfo('key', 'value');
$k->setExtraInfo('key', 'value');

/**
 * 6. Invoke activateReservation and transmit the data.
 */

/* Make sure the order status is ACCEPTED, before activation.
   You can do this by using checkOrderStatus(). */

// Here you enter the reservation number you got from reserveAmount():
$rno = '123456';

try {
    // Transmit all the specified data, from the steps above, to Klarna.
    $result = $k->activateReservation(
        '4103219202',           // PNO (Date of birth for DE and NL).
        $rno,                   // Reservation to activate
        null,                   // Gender.
        '',                     // OCR number to use if you have reserved one.
        KlarnaFlags::NO_FLAG,   // Flags to affect behavior.
        // -1, notes that this is an invoice purchase, for part payment purchase
        // you will have a pclass object which you use getId() from.
        KlarnaPClass::INVOICE
    );

    $risk = $result[0]; // ok or no_risk
    $invno = $result[1];

    echo "risk: {$risk}\ninvno: {$invno}\n";
    // Reservation is activated, proceed accordingly.
} catch(Exception $e) {
    // Something went wrong, print the message:
    echo "{$e->getMessage()} (#{$e->getCode()})\n";
}
<%
    Option Explicit
%>
<!-- Please note that the include below points to the web root -->
<!-- The include has to be modified if example is placed elsewhere -->
<!-- #include virtual="Klarna.asp" -->
<!-- 1. Initialize and setup the Klarna instance -->
<%

    ' Grab the API object
    ' -Merchant ID or Estore ID, an integer above 0.
    ' -The shared secret which accompanied your eid.
    ' -Country, language and currency.
    Dim kAPI
    Set kAPI = GetKlarna(0, "sharedsecret", "SE", "SV", "SEK")

    ' Do we want to see normal debug information?
    kAPI.DebugInformation = True

    ' Set the address and port to Klarna server.
    ' Use LIVE or BETA depending on which server your eid is associated with.
    kAPI.SetPort(HTTPS_PORT) ' or HTTP_PORT
    kAPI.SetHost(BETA_HOST) ' or LIVE_HOST

    ' Where the XML for the PClasses are stored, e.g. "pclasses.xml"
    kAPI.SetPClassesStorageUri(Server.MapPath("pclasses.xml"))
%>
<!-- 2. Add the article(s), shipping and/or handling fee -->
<%

    ' Here we add a normal product to our goods list.
    ' -Quantity
    ' -Article number
    ' -Article name/title
    ' -Price
    ' -VAT, 25% VAT
    ' -Discount
    ' -Flags, price including VAT
    Call kAPI.AddArticle(4, "MG200MMS", "Matrox G200 MMS", 299.99, 25, 0, INC_VAT)

    ' Next we might want to add a shipment fee for the product
    Call kAPI.AddArticle(1, "", "Shipping fee", 40, 25, 0, INC_VAT + IS_SHIPMENT)

    ' Lastly, we want to use an invoice/handling fee as well
    Call kAPI.AddArticle(1, "", "Handling fee", 10, 25, 0, INC_VAT + IS_HANDLING)
%>
<!-- 3. Create and set the address(es) -->
<%

    ' Create the address object.
    Dim address
    Set address = new KlarnaAddr

    ' Specify the customers details.
    address.setEmail("always_accepted@klarna.se")
    address.setTelno("") ' We skip the normal land line phone, only one is needed.
    address.setCellno("0765260000")
    address.setFirstName("Testperson-se")
    address.setLastName("Approved")
    address.setCompanyName("") ' No company name
    address.setCareof("") ' No care of, C/O
    address.setStreet("Stårgatan 1") ' For DE and NL specify street number with setHouseNumber.
    address.setHouseNumber("") ' Only required for DE / NL
    address.setHouseExt("") ' Only required for NL.
    address.setZipCode("12345")
    address.setCity("Ankeborg")
    address.setCountry(COUNTRY_SE)

    ' Next we tell the Klarna instance to use the address in the next order.
    Call kAPI.SetAddress(IS_BILLING, address)  ' Billing / invoice address
    Call kAPI.SetAddress(IS_SHIPPING, address) ' Shipping / delivery address

%>
<!-- 4. Specify relevant information from your store. (OPTIONAL) -->
<%

    ' Set store specific information so you can e.g. search and associate invoices with order numbers.
    ' -Order id 1, maybe the estore's order number/id?
    ' -Order id 2, could be an order number from another system?
    ' -User, Username, email or identifier for the user?
    Call kAPI.SetEstoreInfo("OrderID #1", "OrderID #2", "")

    ' If you don't have the order id available at this stage, you can later use the method updateOrderNo().

%>
<!-- 5. Set additional information. (OPTIONAL) -->
<%

    ' Comment?
    kAPI.SetComment("A text string stored in the invoice commentary area.")

    ' Shipment type?
    ' Normal shipment is defaulted, delays the start of invoice expiration/due-date.
    Call kAPI.SetShipmentInfo("delay_adjust", EXPRESS_SHIPMENT)

    Call kAPI.SetExtraInfo("key", "value")
    Call kAPI.SetIncomeInfo("key", "value")
    Call kAPI.SetShipmentInfo("key", "value")
    Call kAPI.SetTravelInfo("key", "value")

%>
<!-- 6. Invoke activateReservation and transmit the data. -->
<%

    On Error Resume Next

    ' Make sure the order status is ACCEPTED, before activation.
    ' You can do this by using checkOrderStatus().

    ' Here you enter the reservation number you got from ReserveAmount():
    Dim reservationNumber
    reservationNumber = CStr(Request.QueryString("rno"))

    ' Transmit all the specified data, from the steps above, to Klarna.
    ' -pno, Date of birth for DE.
    ' -reservationNumber, Reservation number.
    ' -gender, The customer is a male.
    ' -ocr, If you reserved an OCR number earlier.
    ' -amount, -1 will calculate the amount using the internal goods list.
    ' -flags, No specific behaviour like RETURN_OCR or TEST_MODE.
    ' -pclass, -1, notes that this is an invoice purchase, for part payment purchase you will have a pclass object on which you use getId().
    ' -encoding, null to automatically use it for DE.
    Dim result
    result = kAPI.ActivateReservation("410321-9202", reservationNumber, MALE, -1, NO_FLAG, PCLASS_INVOICE, null, True)

    If Err.number = 0 Then
        ' Success
        Dim risk
        risk = result(0) ' ok or no_risk
        Dim invoiceNumber
        invoiceNumber = result(1)
        Response.Write("Reservation was activated. Invoice number: " & invoiceNumber)
        Response.Write(" / Risk is: " & risk)

        ' Reservation is activated, proceed accordingly.
    Else
        ' Something went wrong
        Response.Write("Error occured: " & Err.number & " - " & Err.Description & "</br>" & Err.Source & "</br>")
    End If

%>
<!-- Finished -->
<%@page import="com.klarna.api.KlarnaEncoding"%>
<%@page import="com.klarna.api.flags.Reservation"%>
<%@page import="com.klarna.api.flags.Shipment"%>
<%@page import="com.klarna.api.InformationType"%>
<%@page import="com.klarna.api.flags.Address"%>
<%@page import="java.util.EnumSet"%>
<%@page import="com.klarna.api.flags.Goods"%>
<%@page import="com.klarna.api.KlarnaLanguage"%>
<%@page import="com.klarna.api.KlarnaCurrency"%>
<%@page import="com.klarna.api.KlarnaCountry"%>
<%@page import="com.klarna.api.KlarnaAddr"%>
<%@page import="com.klarna.api.KlarnaPClass"%>
<%@page import="com.klarna.api.KlarnaConfig"%>
<%@page import="com.klarna.api.Klarna"%>
<%@page contentType="text/html" pageEncoding="ISO-8859-1"%>

<%

    /*
     *  1. Initialize and setup the Klarna instance.
     */
    Klarna k = new Klarna();

    /*
     *  Configure the Klarna object using the config() method. (Alternative 1)
     */

    /* KlarnaConfig conf = new KlarnaConfig();

    // Define values:
    conf.setEid(1);                         // Merchant ID or Estore ID, an Integer above 0.
    conf.setSecret("sharedSecret");         // The shared secret which accompanied your eid.
    conf.setCountry(KlarnaCountry.SE);      // The country of your store.
    conf.setLanguage(KlarnaLanguage.SV);    // The language of your store.
    conf.setCurrency(KlarnaCurrency.SEK);   // The currency of your store.
    conf.setMode(Klarna.BETA);              // or Klarna.LIVE when you are ready to go live.

    // Define pclass settings:
    conf.setPcStorage("json");              // Storage module. Currently only json is supported.
    conf.setPcURI("/srv/pclasses.json");    // Where the json file for the pclasses are stored.

    // Should we use SSL?
    conf.setSsl(false);

    // Should we error report/status report to klarna.
    conf.setCandice(true);                  // set to false if your server doesn't support UDP

    // Do we want to see normal debug information?
    conf.setDebug(null);                    // true to debug, null or false not to debug
    // Set the config object.
    k.config(conf);

     */


    /*
     *  Configure the Klarna object using the config() method (Alternative 2)
     */

    /*
     *   k.config(1,                     // e-store ID
     *           "sharedSecret",         // shared secret
     *           KlarnaCountry.SE,       // Country constant
     *           KlarnaLanguage.SV,      // Language constant
     *           KlarnaCurrency.SEK,     // Currency constant
     *           Klarna.BETA,            // Mode, BETA or LIVE
     *           "json",                 // Storage module
     *           "/srv/pclasses.json",   // Storage location
     *           true,                   // SSL
     *           true                    // Candice
     *           );
     *
     *  k.debug = false;
     */

    /*
     *  Configure the Klarna object using the config() method (Alternative 3)
     */

    k.config(KlarnaConfig.fromJson("klarna.json"));

    /*  the file would contain the following data to set the same information as above alternatives:
     * {
     *      "eid":1,
     *      "secret":"sharedSecret",
     *      "country":"SE",
     *      "language":"SV",
     *      "currency":"SEK",
     *      "mode":1,
     *      "ssl":false,
     *      "candice":true,
     *      "pcStorage":"json",
     *      "pcURI":"/srv/pclasses.json"
     *  }
     *
     */

    /*
     *  Configure with the constructor right away. Minimal constructor showed here.
     */
    // MySQLStorage mysql = new MySQLStorage("user", "password", "address", "dbname", "dbtable", 3306);
    // Klarna klarna = new Klarna(1, "sharedSecret", KlarnaCountry.SE, KlarnaCurrency.SEK, mysql, Klarna.BETA);

    /*
     *  2. Add the article(s), shipping and/or handling fee.
     */

    //  Here we add a normal product to our goods list.

    k.addArticle(1, // Quantity
            "MG200MMS", // Article number
            "Matrox G200 MMS", // Article name/title
            299.99, // Price
            19d, // 19% VAT. a double
            0d, // Discount, a double
            Goods.INC_VAT);// Price is including VAT

    //Next we might want to add a shipment fee for the product
    EnumSet<Goods> goodsflags = EnumSet.of(Goods.INC_VAT, Goods.IS_SHIPMENT); // Some flags can be added together.
    k.addArticle(1,
            "shipfee",
            "Shipping fee",
            4.5,
            19d,
            0d,
            goodsflags);   // Price is including VAT and is shipment fee

    k.addArticle(1,
            "handlingfee",
            "Handling fee",
            1.5,
            19d,
            0d, // things kan be added aswell directly in the method call.
            Goods.INC_VAT.toInt() + Goods.IS_HANDLING.toInt());   // Price is including VAT and is handling/invoice fee


    /*
     * 3. Create and set the address(es).
     */

    //Create the address object and specify the values.
    KlarnaAddr addr = new KlarnaAddr(
            "always_accepted@klarna.com", // Email address
            "", // We skip the normal land line phone. only one is needed.
            "4676520000", // Mobile number
            "Testperson-se", // First (given) name
            "Approved", // Last (family) name
            "", // no care of ( c/o )
            "Stårgatan 1", // for DE and NL specify street number in houseNo
            "12345", // Zip code
            "Ankeborg", // City
            KlarnaCountry.SE, // KlarnaCountry constant
            null,
            null);

    //There are also set/get methods to do the same thing, like:
    addr.setEmail("always_accepted@klarna.com");

    // Next we tell the klarna instance to use the address in the next order.
    k.setAddress(Address.IS_BILLING, addr);     // Billing / invoice address
    k.setAddress(Address.IS_SHIPPING, addr);    // Shipping / delivery address

    /*
     *  4. Specify relevant information from your store. (OPTIONAL)
     */

    k.setEstoreInfo(
            "987654", // Maybe the estores order number/id
            "1234567890", // Could be an order number from another system?
            "" // Username, email or identifier for the user?
            );
    // another option is to omit the last field entirely.

    //If you don't have the order id available at this stage, you can later use the method updateOrderNo().

    /*
     *  5. Set additional informaion (OPTIONAL)
     */
    // A comment maybe?
    k.setComment("A text string stored in the invoice commentary area.");

    // Shipment type?
    k.setAdditionalInformation(InformationType.SHIPMENT, "delay_adjust", Shipment.EXPRESS_SHIPMENT);

    /*
     *  6. Invoke activateReservation and transmit the data.
     */
    /* Make sure the order status is ACCEPTED, before activation.
    You can do this by using checkOrderStatus(). */

    // Here you enter the reservation number you got from reserveAmount():
    String rno = request.getParameter("reservation_number");

    // Set clients IP address
    k.setClientIP(request.getRemoteAddr());
    try {
        // add together the flags to be used.
        EnumSet<Reservation> flags = EnumSet.of(Reservation.NO_FLAG);

        //Transmit all the specified data, from the steps above, to Klarna.
        String[] result = k.activateReservation("410321-9202", // Date of Birth
                rno, // reservation number
                null, // gender, null if not specified
                "", // optional OCR number
                flags, // Flags affecting the behavior
                KlarnaPClass.INVOICE, // PClass ID, or KlarnaPClass.INVOICE for an invoice.
                KlarnaEncoding.PNO_SE, // Optional Encoding, defaulted to use whatever suits the country configured.
                true); // Optional parameter to clear the settings or not after purchase. Defaulted to true.

        String risk = result[0];     //ok or no_risk
        String invNo = result[1];

        out.println("Risk: " + risk);
        out.println("invNo: " + invNo);

        //Reservation is activated, proceed accordingly.

    } catch (Exception e) {
        //Something went wrong, print the message:
        out.println("Error: " + e.getMessage());
        out.println(e);
    }

%>
// ----------------------------------------------------------------------------
// <copyright file="ActivateReservationExample.cs" company="Klarna AB">
//    Copyright 2013 Klarna AB
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// <author>Klarna Support: support@klarna.com</author>
// <link>http://integration.klarna.com/</link>
// ----------------------------------------------------------------------------
namespace KlarnaDotNetApi.Examples
{
    using System;
    using Klarna.Api;

    /// <summary>
    /// This is an example of how to use the ActivateReservation call.
    /// </summary>
    public class ActivateReservationExample : IExample
    {
        /// <summary>
        /// Method to run the example
        /// </summary>
        public void Run()
        {
            ////------------------------------------------------------------
            // 1. Initialize and setup the API instance.
            ////------------------------------------------------------------

            Configuration configuration = new Configuration(
                Country.Code.SE, Language.Code.SV, Currency.Code.SEK,
                Encoding.Sweden)
            {
                Eid = 0,
                Secret = "sharedsecret",
                IsLiveMode = false
            };

            Api api = new Api(configuration);
            api.PClassStorageUri = @"pclasses.xml";

            // It's important to set the end customers IP address
            api.ClientIp = "192.0.2.9";

            ////------------------------------------------------------------
            // 2. Add the article(s), shipping and/or handling fee.
            ////------------------------------------------------------------

            api.AddArticle(
                4, "1234e", "Matrox G200 MMS", 299.99, 25, 0,
                GoodsFlags.IncVAT);

            api.AddArticle(
                1, string.Empty, "Shipment fee", 20.0, 25, 0,
                GoodsFlags.Shipping | GoodsFlags.IncVAT);

            api.AddArticle(
                1, string.Empty, "Handling fee", 10.0, 25, 0,
                GoodsFlags.Handling | GoodsFlags.IncVAT);

            ////------------------------------------------------------------
            // 3. Create and set the address(es).
            ////------------------------------------------------------------

            api.ShippingAddress = new Address()
            {
                Email = "pending_approved@shipping.xxx",
                PhoneNumber = string.Empty,
                CellPhoneNumber = "0765260000",
                FirstName = "Testperson-se",
                LastName = "Approved",
                Street = "Stårgatan 1",
                CareOf = string.Empty,
                ZipCode = "12345",
                City = "Ankeborg",
                Country = Country.Code.SE,
                HouseNumber = string.Empty,
                HouseExtension = string.Empty,
                CompanyName = string.Empty
            };

            api.BillingAddress = new Address()
            {
                Email = "pending_approved@billing.xxx",
                PhoneNumber = string.Empty,
                CellPhoneNumber = "0765260000",
                FirstName = "Testperson-se",
                LastName = "Approved",
                Street = "Stårgatan 1",
                CareOf = string.Empty,
                ZipCode = "12345",
                City = "Ankeborg",
                Country = Country.Code.SE,
                HouseExtension = string.Empty,
                CompanyName = string.Empty
            };

            ////------------------------------------------------------------
            // 4. Invoke ActivateReservation and transmit the data.
            ////------------------------------------------------------------

            Console.WriteLine("Please enter reservation number and press Enter");
            string reservationNumber = Console.ReadLine();

            try
            {
                ActivateReservationResponse response = api.ActivateReservation(
                    "410321-9202", reservationNumber, Gender.Male, string.Empty, 
                    ReservationFlags.NoFlag);

                Console.WriteLine("Successfully activated the reservation.");
                Console.WriteLine(string.Format(
                    "Invoice number: {0}", response.InvoiceNumber));
                Console.WriteLine(string.Format(
                    "Risk status: {0}", response.RiskStatus));
            }
            catch (KlarnaException ex)
            {
                Console.WriteLine("An error occurred during the call to Klarna");
                Console.WriteLine("Error code: {0}", ex.ErrorCode);
                Console.WriteLine("Error description: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "An exception occurred during the call to Klarna");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}

Input data:

  Variable Type Description
Required rno string Reservation number
  ocr string An ocr number. Please ask for more information from your integration sales contact.
Required pno/birthdate string Use the following format:

Sweden: yymmdd-nnnn, it can be sent with or without dash "-" or with or without the two first numbers in the year.
Finland: ddmmyy-nnnn
Denmark: ddmmyynnnn
Norway: ddmmyynnnnn
Germany: ddmmyyyy
Austria: ddmmyyyy
Netherlands: ddmmyyyy

d = day, m = month, y = year, n = person specific numbers

If it is a purchase with a company registration number, the reference person can be typed in the first and last name fields. If a social security number/birth date belongs to a person under 18 or if the social security number/birth date is invalid, Klarna will not make a credit report and will instead return an error status.
  gender integer The customer's gender (0=female, 1=male). Required for purchases in Germany and Netherlands.
  reference string The reference person for the purchase if it is a company purchase. You can also use this field to write a message or other important information to the customer on the invoice.
  reference_code string The reference code for the sale. You can also use this field to write a message or other important information to the customer on the invoice.
  orderid1 string Orderid
  orderid2 string Orderid
Required delivery_addr array Delivery Address created using setAddress function. Please observe that for Sweden the address must be exactly as you receive with getAddresses function.
Required billing_addr array Invoicing Address using setAddress function.
Required client_ip string IP number when the purchase is made online, otherwise “0.0.0.0” (used to avoid fraud).
Required flags integer Flag which affects the invoiced purchase. Input 0 to set no flag.

KRED_TEST_MODE (value: 2) If you set this flag, a test invoice is set despite your store working in live mode. It comes in handy if you wish to test something while avoiding any disturbance to your regular invoicing.

KRED_SEND_BY_MAIL (value: 4) To send the invoice by mail

KRED_SEND_BY_EMAIL (value: 8) To send the invoice by e-mail

KRED_PRESERVE_RESERVATION (value: 16) To make a part activation of a reservation. You can use the same reservation number for the following activations.

//Klarna Mobile flags
KRED_PHONE_TRANSACTION (value: 512) To tell Klarna that it's a phone transaction
KRED_SEND_PHONE_PIN (value: 1024): To send the customer a PIN code.
Required currency integer Currency code to be used for the invoices.

Swedish krona: KRED_SEK (value: 0)
Norwegian krona: KRED_NOK (value: 1)
Euro: KRED_EUR (value: 2)
Danish krona: KRED_DKK (value: 3)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required country integer Code for the country where your sales will be in:

Sweden: KRED_ISO3166_SE (value: 209)
Finland: KRED_ISO3166_FI (value: 73)
Denmark: KRED_ISO3166_DK (value: 59)
Norway: KRED_ISO3166_NO (value: 164)
Germany: KRED_ISO3166_DE (value: 81)
Austria: KRED_ISO3166_AT (value: 15)
Netherlands: KRED_ISO3166_NL (value: 154)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required language integer Language code for the language used on the invoice.


Swedish: KRED_ISO639_SV (value: 138)
Norwegian: KRED_ISO639_NB (value: 97)
Finnish : KRED_ISO639_FI (value: 37)
Danish: KRED_ISO639_DA (value: 27)
German: KRED_ISO639_DE (value: 28)
Austria: KRED_ISO639_DE (value: 28)
Dutch: KRED_ISO639_NL (value: 101)

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required eid integer An e-store ID which refers to your store in Klarna's database.
Required secret string A shared secret which is used to secure all traffic between Klarna and your store.
Required pno_encoding integer Indicates the country where the person/customer is registered in:

Sweden: value: 2
Norway: value: 3
Finland: value: 4
Denmark: value: 5
Germany: value: 6
Austria: value: 8
Netherlands: value: 7

Please note: Currency, country and language must be the same as where the customer is registered in. E.g. Swedish customer, SEK, Sweden and Swedish.
Required pclass integer This argument designates campaign code to be used at the purchase and is utilized when the sale is a part payment or a special campaign purchase. If the sale is an invoice purchase this argument shall be set to -1.

-1 = invoice
xxx = campaign
xxx = all other pclasses*

Please note that part payment and special campaign purchases are not available for companies.

*There are two ways to retrieve pclasses.

1. Go to Klarna Online and press "view store" button in the menu on the left. In the store view, click "Click here to view campaigns".

2. Use the function fetchPClasses to save all pclass values to your database.
Required goodsList array A list of goods. Every listed item is created using the addArticle function.
  comment string A text string stored in the invoice commentary area.
Required shipmentinfo array [delay_adjust] Required
  • (int) - The two values determine how long after invoice activation Klarna starts countdown to the expiration date. Both countdowns are by default zero days. The time of the countdowns can be negotiated with Klarna.

    KRED_NORMAL_SHIPMENT (value: 1) KRED_EXPRESS_SHIPMENT (value: 2).
     
  travel_info array Not used at this moment
  income_expense array [yearly_salary]
  • (int) - Customer's yearly salary. This was once required in Denmark.
    Since March 2012 we no longer require this information, it can be left empty and does not need to be supplied at all.
     
  bank_info array Not used at this moment
  session_id array [dev_id_1]
  • (string) -
     
[dev_id_2]
  • (string) -
     
[dev_id_3]
  • (string) -
     
[beh_id_1]
  • (string) -
     
[beh_id_2]


     
[beh_id_3]
  • (string) -
  extra_info array [cust_no]
  • (string) - The customer number in the estores system
     
[bclass]
  • (int) - This value is set per store when needed. Consult your integration technician if you will use this value.
     
[pin]
  • (string) - If you are using Klarna Mobil you send the customers pin code here. Otherwise you only use an empty string.