Embed the Checkout snippet

This tutorial starts when the consumer has selected their product(s) on your site, and wants to go to your checkout.

In the steps below, you will be guided in how to render the Klarna Checkout HTML snippet on your checkout page. The Checkout snippet is where the consumer enter their address details and completes their payment with one of the payment methods offered within the checkout.

 

1. Add the cart items

You need to first prepare the order data by adding the consumer's cart items according to the API reference. The example code below is populated with example data for the test order.

Note: Find out more about the different fields in the cart items list in the API reference.

$orderData = array();

$orderData['order_lines'] = array(
    array(
        "type" => "physical",
        "reference" => "123050",
        "name" => "Tomatoes",
        "quantity" => 10,
        "quantity_unit" => "kg",
        "unit_price" => 600,
        "tax_rate" => 2500,
        "total_amount" => 6000,
        "total_tax_amount" => 1200
    ),
    array(
        "type" => "physical",
        "reference" => "543670",
        "name" => "Bananas",
        "quantity" => 1,
        "quantity_unit" => "bag",
        "unit_price" => 5000,
        "tax_rate" => 2500,
        "total_amount" => 4000,
        "total_discount_amount" => 1000,
        "total_tax_amount" => 800
    )
);
final List<OrderLine> lines = new ArrayList<OrderLine>() {
    {
        add(new OrderLine()
                .setType("physical")
                .setReference("123050")
                .setName("Tomatoes")
                .setQuantity(10L)
                .setQuantityUnit("kg")
                .setUnitPrice(600L)
                .setTaxRate(2500)
                .setTotalAmount(6000L)
                .setTotalTaxAmount(1200L));
        add(new OrderLine()
                .setType("physical")
                .setReference("543670")
                .setName("Bananas")
                .setQuantity(1L)
                .setQuantityUnit("bag")
                .setUnitPrice(5000L)
                .setTaxRate(2500)
                .setTotalAmount(4000L)
                .setTotalDiscountAmount(1000L)
                .setTotalTaxAmount(800L));
    }
};
OrderLine orderLine = new OrderLine
{
    Type = "physical",
    Reference = "123050",
    Name = "Tomatoes",
    Quantity = 10,
    QuantityUnit = "kg",
    UnitPrice = 600,
    TaxRate = 2500,
    TotalAmount = 6000,
    TotalTaxAmount = 1200
};

OrderLine orderLine2 = new OrderLine
{
    Type = "physical",
    Reference = "543670",
    Name = "Bananas",
    Quantity = 1,
    QuantityUnit = "bag",
    UnitPrice = 5000,
    TaxRate = 2500,
    TotalAmount = 4000,
    TotalDiscountAmount = 1000,
    TotalTaxAmount = 800
};

List<OrderLine> orderLines = new List<OrderLine>
{
    orderLine,
    orderLine2
};

2. Configure the checkout order

Next, you need to set some configuration details to reflect your website settings. These are the items you should configure:

  • Specify the merchant ID and shared secret that you received when you applied for API credentials.
  • Set the currency, language and country to be used.
  • Add URLs to where you host different pages used by Klarna Checkout.
    • Terms: The URL for your terms and conditions. Mandatory.
    • Checkout: URL to your checkout page. Mandatory.
    • Confirmation: URL to your confirmation page. This is where customers will be redirected after completing their purchase. Mandatory.
    • Push: URL to which Klarna will send an HTTP post request to confirm the order. Mandatory.
    • Order validation, Tax & Shipping changes and other order notifications. Find out more in the API reference on the Merchant URL object

Find out more about the different configurations in our API reference.

$merchantUrls = [
    'terms' =>  'http://terms',
    'checkout' =>  'http://checkout?klarna_order_id={checkout.order.id}',
    'confirmation' =>  'http://confirmation?klarna_order_id={checkout.order.id}',
    'push' =>  'http://push?klarna_order_id={checkout.order.id}'
];

$orderData['purchase_country'] = 'gb';
$orderData['purchase_currency'] = 'gbp';
$orderData['locale'] = 'en-US';
$orderData['order_amount'] = 10000;
$orderData['order_tax_amount'] = 2000;

$orderData['merchant_urls'] = $merchantUrls;
final MerchantUrls urls = new MerchantUrls()
{
    {
        setTerms(
            "http://terms");
        setCheckout(
            "http://checkout?klarna_order_id={checkout.order.id}");
        setConfirmation(
            "http://confirmation?klarna_order_id={checkout.order.id}");
        setPush(
            "http://push?klarna_order_id={checkout.order.id}");
    }
};

CheckoutOrderData orderData = new CheckoutOrderData()
{
    {
        setPurchaseCountry("gb");
        setPurchaseCurrency("gbp");
        setLocale("en-US");
        setOrderAmount(10000L);
        setOrderTaxAmount(2000L);
        setOrderLines(lines);
        setMerchantUrls(urls);
    }
};
MerchantUrls merchantUrls = new MerchantUrls
{
    Terms = new System.Uri(
        "http://www.merchant.com/toc"),
    Checkout = new System.Uri(
        "http://checkout?klarna_order_id={checkout.order.id}"),
    Confirmation = new System.Uri(
        "http://confirmation?klarna_order_id={checkout.order.id}"),
    Push = new System.Uri(
        "http://push?klarna_order_id={checkout.order.id}")
};

CheckoutOrderData orderData = new CheckoutOrderData()
{
    PurchaseCountry = "gb",
    PurchaseCurrency = "gbp",
    Locale = "en-US",
    OrderAmount = 10000,
    OrderTaxAmount = 2000,
    OrderLines = orderLines,
    MerchantUrls = merchantUrls
};

Note: Change the locale and purchase country/currency to the match the customer experience you want to render.

If a checkout session already exists, you should use the already configured order in that session instead of adding the configuration data again to provide a better user experience.

Optimize the checkout for returning customers

When you render the checkout snippet you may add data about the consumer. We recommend using this feature for consumers who log into an account on your page where you already have stored data about the consumer. If you choose to add consumer data, the consumer will not need to re-enter the data into the checkout, and your conversion will increase. In the API resource structure you will find what data you can add.


3. Create a checkout order

When all configuration data and the cart items have been set, it’s time to create an order in Klarna’s system.

Note: If a checkout session already exists you should use the order in that session instead of creating a new one.

$connector = \Klarna\Rest\Transport\Connector::create(
    'merchantId',
    'sharedSecret',
    \Klarna\Rest\Transport\ConnectorInterface::EU_TEST_BASE_URL
);

$checkout = new \Klarna\Rest\Checkout\Order($connector);
$checkout->create($orderData);
Client client = DefaultClient.newInstance(
    "merchantId",
    "sharedSecret",
    Client.EU_TEST_BASE_URL);
CheckoutOrder checkout = client.newCheckoutOrder();

checkout.create(orderData);
IConnector connector = ConnectorFactory.Create(
    "merchantId",
    "sharedSecret",
    Client.EuTestBaseUrl);
Client client = new Client(connector);

ICheckoutOrder checkout = client.NewCheckoutOrder();
checkout.Create(orderData);

4. Render the checkout snippet

It's now time to render the checkout snippet.

To do so, you now fetch the order from Klarna’s system and store the order ID in the session. The checkout order now contains an HTML snippet under the html_snippet property. You should extract the HTML snippet and display it on your checkout page.

$checkout->fetch();
echo "<div>{$checkout['html_snippet']}</div>";
CheckoutOrderData orderData = checkout.fetch();
out.println(String.format("<div>%s</div>", orderData.getHtmlSnippet()));
CheckoutOrderData orderData = checkout.Fetch();
Response.Write(string.Format("<div>{0}</div>", orderData.HtmlSnippet));

 

This is what it should look like:

 


5. Handling an existing order

You should keep track of the Klarna order id associated with the current customer to avoid creating a new order every time the customer loads the checkout page. This will allow the customer to reload the checkout page without having to reenter any information they have already entered. 

When the customer loads the checkout page and have a Klarna order id associated with their session you should fetch the order from Klarna. If the order content has changed you should make an update to the order.

Note: See the update order page for information on how to update an order.

Retrieve the order

Use the checkout order ID to fetch the order from Klarna.

$merchantId = 0;
$sharedSecret = 'sharedSecret';
$orderId = '12345';

$connector = \Klarna\Rest\Transport\Connector::create(
    $merchantId,
    $sharedSecret,
    \Klarna\Rest\Transport\ConnectorInterface::EU_TEST_BASE_URL
);

$checkout = new \Klarna\Rest\Checkout\Order($connector, $orderId);

$checkout->fetch();
Client client = DefaultClient.newInstance(
    "merchantId", 
    "sharedSecret", 
    Client.EU_TEST_BASE_URL)

CheckoutOrder checkout = client.newCheckoutOrder("12345");
CheckoutOrderData orderData = checkout.fetch();
IConnector connector = ConnectorFactory.Create(
    "merchantId", 
    "sharedSecret", 
    Client.EuTestBaseUrl);

Client client = new Client(connector);

ICheckoutOrder checkout = client.NewCheckoutOrder("123456");
CheckoutOrderData orderData = checkout.Fetch();

 


Validating the order before it is completed

For a number of different reasons there could be a need to validate the order before it is completed. This can be done using a callback that Klarna will call when the customer clicks the buy button. Find out more in the documentation.

 

What's next?

You have integrated Klarna Checkout into your checkout page.

The next step is to render the confirmation snippet.