alt

Important information

The API reference is now available here.
The deprecated API reference is available here.

Unzer

Accept Klarna with UI components

Use Unzer UI component to add Klarna payment to your checkout page.

Overview

Using UI components for Klarna, create a payment type resource that is later used to make the payment. You don’t need any form fields for this payment method. You can check a demo version of the component here. Basic steps for integrating using UI components are the same for all payment methods and you can read about them here.

With Klarna, you must provide information about the customer using a customers resource and the purchased products using a basket resource when you make the transaction. This is required for customer assessment and transaction approval. You will also need the customer information to create the Klarna invoice document. You are responsible for gathering this data during the checkout.

Before you begin

Step 1: Add UI components to your payment page
client side

First, you need to initiate our UI components library and add the payment form to your payment page.

Initiate UI component

Load our JS script and CSS stylesheet

Include Unzer’s script and stylesheet on your website.

Always load the script and stylesheet directly from Unzer:

<link rel="stylesheet" href="https://static.unzer.com/v1/unzer.css" />
<script type="text/javascript" src="https://static.unzer.com/v1/unzer.js"></script>
icon
Faster load time
To make your website load faster, insert JavaScript scripts at the bottom of your HTML document.
icon
Importing Unzer styles
To minimize the risk of Unzer styles affecting the styles of your webpage, we suggest putting unzer.css on top of other imported CSS files.

Create an Unzer instance

Create an unzer instance with your public key:

// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx');
icon
Placeholder keys
In the previous example, we used a placeholder API key for example purposes. You should replace it with your public key.

Localization and languages

We support localization with locale option parameters. Check the Localization page for a list of all the supported locales.

The auto option (applied by default) uses the client’s browser language.

Here you can see how to set the language, in our case ‘de-DE’ - to do so, add a comma separated parameter to your unzer instance:

// Creating an unzer instance with your public key
var unzerInstance = new unzer('s-pub-xxxxxxxxxx', {locale: 'de-DE'});

Implement the payment form

Option 1: Implement with customer form

If you don’t have information about the customer (and the corresponding customer ID) or want to update information of an already existing customer, you can do so using the customer form. Check the Customer UI component page for more information.

Insert the customer form

To use the customer form effectively, you must insert it into your payment form. We recommend placing it above the payment elements.

Here is an example:

<form id="payment-form">
    <div id="customer" class="field">
        <!-- The customer form UI element will be inserted here -->
    </div>
    <div id="error-holder" class="field" style="color: #9f3a38">
        <!-- Errors will be inserted here -->
    </div>
    <button class="unzerUI primary button fluid" id="submit-button" type="submit">
      Pay
    </button>
</form>

Create the customer resource

A customer resource is created like a payment type with the UI components. Please make sure to set the option paymentTypeName to allow rendering a specialized form for this payment type.

let customer = unzerInstance.Customer();
customer.create({containerId: 'customer', paymentTypeName: 'klarna'});

Update the customer resource

To render the customer form, you will need to call the Customer.update() function instead of Customer.create(). In case you want to initialize the form with the data of an already created customer, you will need to call the Customer.initFormFields() function before calling Customer.update().

let customer = unzerInstance.Customer();

// Initialize customer form with existing B2C customer data
customer.initFormFields({
  "salutation": "mr",
  "firstname": "Rainer",
  "lastname": "Zufall",  
  "birthDate": "1980-06-22",
  "email": "rainer.zufall@domain.de",
  "language": "de",
  "phone": "+49 152 987654321",
  "billingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  },
  "shippingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  }
})

// Call the update function that will initialize the form with existing customer data
// You need to pass the customerId, and the containerId
customer.update('s-cst-b7e502fcbb10', {
  containerId: 'customer',
})

Optionally, you can add a custom event listener that sends the validation result of all input fields

// Note: the event listener has to be called before the `update()` call
customer.addEventListener('validate', function(e) {
  if (e.success) {
    // run some code (for example, enable the `pay` button)
  } else {
    // run some code (for example, disable the `pay` button)
  }
})

Option 2: Create the customer on the server side

You can also use the customer data provided by your shop system to create the customer resource on the server side. This way you can omit rendering the customer form in the front end and create the resource and use the ID in your transaction request. Go to the section Create customer resource for more details.

You need to render the payment type form and create a simple HTML button on the client side:

<form id="payment-form">
    <div id="error-holder" class="field" style="color: #9f3a38">
        <!-- Errors will be inserted here -->
    </div>
    <button class="unzerUI primary button fluid" id="submit-button" type="submit">Pay</button>
</form>

Create the payment type resource

To create a payment type resource – a Klarna instance, call the unzerInstance.Klarna() function:

let klarna = unzerInstance.Klarna();

Add an event listener and submit the form

Option 1: With the customer create form

Get the HTML form by its unique ID and add an event listener.

Create a Promise for the customer and the klarna object and handle them with Promise.all(). Please Check Customer form with payment for more information for more information.

let form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();

        let customerPromise = customer.createCustomer();
        let klarnaPromise = klarna.createResource();
        Promise.all([klarnaPromise, customerPromise])
            .then(function(values) {
                let typeId = values[0].id;
                let customerId = values[1].id;
                // Submit the IDs to your server-side integration.
            })
            .catch(function(error) {
              document.getElementById('error-holder').innerText = error.customerMessage || error.message || 'Error'
            })
    });

With the customer update form

Get the HTML form by its unique ID and add an event listener.

Create a Promise for the customer and the klarna object and handle them with Promise.all(). Please Check Customer form with payment for more information for more information.

let form = document.getElementById('payment-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();

        let customerPromise = customer.updateCustomer();
        let klarnaPromise = klarna.createResource();
        Promise.all([klarnaPromise, customerPromise])
            .then(function(values) {
                let typeId = values[0].id;
                let customerId = values[1].id;
                // Submit the IDs to your server-side integration.
            })
            .catch(function(error) {
              document.getElementById('error-holder').innerText = error.customerMessage || error.message || 'Error'
            })
    });

Option 2: Without the customer form

Get the HTML form by its unique ID and add an event listener.

Inside, create a Promise on the klarna object. The Promise gets either resolved or rejected:

let form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
    event.preventDefault();

    klarna.createResource()
        .then(function(result) {
            let typeId = result.id;
            // submit the payment type ID to your server-side integration
        })
        .catch(function(error) {
          document.getElementById('error-holder').innerText = error.customerMessage || error.message || 'Error'
        })
});

Step 2: Make a payment 
server side

To make a payment, you need a customer, a basket, and a paymentType resource.

Make an authorize transaction and forward the customer to the redirect URL to complete the payment. Initially the transaction will be pending and a paymentId referring to this payment is created.

Create the customer resource

This step is only applicable if you didn’t create a customer resource on the client side.

B2C customer creation

For B2C transactions, create a customer as described in the example request. To learn more about the customer resource, see the API reference.

POST https://api.unzer.com/v1/customers
{
  "salutation": "mr",
  "firstname": "Rainer",
  "lastname": "Zufall",  
  "birthDate": "1980-06-22",
  "email": "rainer.zufall@domain.de",
  "language": "de",
  "phone": "+49 152 987654321",
  "billingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  },
  "shippingAddress": {
    "name": "Rainer Zufall",
    "street": "Unzerstraße 18",
    "zip": "22767",
    "city": "Hamburg",
    "country": "DE"
  }
}
$address = (new Address())
    ->setName('Rainer Zufall')
    ->setStreet('Unzerstraße 18')
    ->setZip('22767')
    ->setCity('Hamburg')
    ->setCountry('DE');

$customer = (new Customer())
    ->setFirstname('Rainer')
    ->setLastname('Zufall')
    ->setSalutation(Salutations::MR)
    ->setCompany('Unzer GmbH')
    ->setBirthDate('1972-12-24')
    ->setEmail('rainer.zufall@domain.de')
    ->setLanguage("de")
    ->setPhone('+49 152 987654321')
    ->setBillingAddress($address)
    ->setShippingAddress($address);

$unzer = new Unzer('s-priv-xxxxxxxxxx');
$unzer->createCustomer($customer);
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");

Address address = new Address()
        .setName('Rainer Zufall')
        .setStreet('Unzerstraße 18')
        .setZip('22767')
        .setCity('Hamburg')
        setCountry('DE');
        
Customer customer = new Customer("John", "Doe")
        .setSalutation(Salutations::MR)
        .setCompany('Unzer GmbH')
        .setBirthDate('1972-12-24')
        .setEmail('rainer.zufall@domain.de')
        .setLanguage("de")
        .setPhone('+49 152 987654321')
        .setBillingAddress(address)
        .setShippingAddress(address);

unzer.createCustomer(customer);

The response looks similar to the following example:

{
    "id": "s-cst-b7e502fcbb10"
}

For a full description of customer resource, refer to the relevant server-side-integration documentation page: Manage customer (direct API calls).

Create a basket resource

The basket resource stores information about the purchased products, used vouchers, and the shipment costs.

For a full description of baskets resource, refer to the relevant server-side-integration documentation page: Manage baskets (v2).

POST https://api.unzer.com/v2/baskets
{
    "totalValueGross": "105.95",
    "currencyCode": "EUR",
    "basketItems": [
        {
            "type": "goods",
            "basketItemReferenceId": "SKU-1783746",
            "title": "Jacket Fleece size M",
            "quantity": 1,
            "amountPerUnitGross": 100,
            "vat": "19"
        },
        {
            "type": "shipment",
            "basketItemReferenceId": "express-shipping",
            "title": "Shipment fee",
            "quantity": 1,                        
            "amountPerUnitGross": 5.95,
            "vat": "19"
        }
    ]
}
<?php
$unzer = new Unzer('s-priv-xxxxxxxxxx');

$basketItem1 = (new BasketItem())
    ->setBasketItemReferenceId('Item-d030efbd4963')
    ->setQuantity(10)
    ->setUnit('m')
    ->setAmountPerUnitGross(20.00)
    ->setAmountDiscountPerUnitGross(1.00)
    ->setVat(19.0)
    ->setTitle('SDM 6 CABLE')
    ->setSubTitle('This is brand new Mid 2019 version')
    ->setImageUrl('https://a.storyblok.com/f/91629/x/1ba8deb8cc/unzer_primarylogo__white_rgb.svg')
    ->setType(BasketItemTypes::GOODS);

$basketItem2 = (new UnzerSDK\Resources\EmbeddedResources\BasketItem())
    ->setTitle('Shipment fee')
    ->setBasketItemReferenceId('express-shipping')
    ->setQuantity(1)
    ->setAmountPerUnitGross(5.95)
    ->setVat(19.0)
    ->setType(UnzerSDK\Constants\BasketItemTypes::SHIPMENT);

$basket = (new Basket())
    ->setTotalValueGross(195.95)
    ->setCurrencyCode('EUR')
    ->setOrderId('Order-12345')
    ->setNote('Test Basket')
    ->addBasketItem($basketItem1)
    ->addBasketItem($basketItem2);

$unzer->createBasket($basket);
BasketItem basketItem1 = new BasketItem()
        .setBasketItemReferenceId("Item-d030efbd4963")
        .setQuantity(BigDecimal.valueOf(10))
        .setUnit("m")
        .setAmountPerUnitGross(BigDecimal.valueOf(20.00))
        .setAmountDiscountPerUnitGross(BigDecimal.valueOf(1.00))
        .setVat(BigDecimal.valueOf(19.0))
        .setTitle("SDM 6 CABLE")
        .setSubTitle("This is brand new Mid 2019 version")
        .setImageUrl(new URL("https://a.storyblok.com/f/91629/x/1ba8deb8cc/unzer_primarylogo__white_rgb.svg"))
        .setType(BasketItem.Type.GOODS);

BasketItem basketItem2 = (new BasketItem())
    .setBasketItemReferenceId("express-shipping")
    .setQuantity(1)
    .setAmountPerUnitGross(BigDecimal.valueOf(5.95))
    .setVat(BigDecimal.valueOf(19.0))
    .setTitle("Shipment fee")
    .setType(BasketItem.Type.GOODS);

Basket basket  = new Basket()
    .setTotalValueGross(BigDecimal.valueOf(195.95))
    .setCurrencyCode(Currency.getInstance("EUR"))
    .setOrderId("Order-12345")
    .setNote("Test Basket")
    .addBasketItem(basketItem1)
    .addBasketItem(basketItem2);

Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
unzer.createBasket(basket);

The response looks similar to the following example:

{
    "id": "s-bsk-7e772dd4266b"
}

For a full description of basket resource, refer to the relevant server-side-integration documentation page: Direct API integration.

Make an authorize transaction

Now, make an authorize transaction with the klarna resource that you created earlier. The response contains a redirect URL where the customer must be redirected to complete the payment.

ParameterTypeDescription
amount (required)floatThe authorization amount
currency (required)stringThe authorization currency, in the ISO 4217 alpha-3 format
returnURL (required)stringThe return URL where the customer must be redirected after a charge transaction.
orderID(required)stringThis is used to send the order ID from your shop to the API
customerId (required)stringThe ID of the customer resource to be used
basketId (required)stringThe basket ID for the payment
typeId (required)stringThe ID of the payment type resource to be used
additionalTransactionData
termsAndConditionUrl (required)stringThe link to the terms and conditions URL of your web-shop.
privacyPolicyUrl (required)stringThe link to the privacy policy for your web-shop.
POST: https://api.unzer.com/v1/payments/authorize
{
    "amount": "105.95",
    "currency": "EUR",
    "returnUrl": "https://www.merchant.com/returnUrl.php",
    "orderId": "{{random_Order_Id}}",
    "resources": {
        "typeId": "s-kla-gixitbjxdm5c",
        "basketId": "s-bsk-7e772dd4266b",
        "customerId": "s-cst-6c8fe4e63bf9"
    },
    "additionalTransactionData": {
        "termsAndConditionUrl": "https://www.merchant.com/terms.html",
        "privacyPolicyUrl": "https://www.merchant.com/privacy-policy.html"
    }
}
$unzer = new Unzer('s-priv-xxxxxxxxxx');
$authorize = (new Authorization(105.95, 'EUR', 'https://www.merchant.com/returnUrl.php'))
    ->setPaymentReference("Example Reference")
    ->setTermsAndConditionUrl('https://www.merchant.com/terms.html')
    ->setPrivacyPolicyUrl('https://www.merchant.com/privacy-policy.html')
    ->setOrderId("ExampleOrderId1234");

$unzer->performAuthorization($authorize, $klarna, $customer, null, $basket);
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
Authorization authorization = (Authorization) new Authorization()
    .setAmount(BigDecimal.valueOf(105.95))
    .setCurrencyCode(Currency.getInstance("EUR"))
    .setReturnUrl("https://www.merchant.com/returnUrl")
    .setOrderId("ExampleOrderId1234")
    .setAdditionalTransactionData(
      new AdditionalTransactionData()
        .setTermsAndConditionsUrl("https://www.merchant.com/terms.html")
        .setPrivacyPolicyUrl("https://www.merchant.com/privacy-policy.html")
    );
unzer.authorize(authorization);

The response looks similar to the following example:

GET: https://api.unzer.com/v1/payments/{{random_Order_Id}}/authorize/{{auth-Id}}
{
    "id": "s-aut-1",
    "isSuccess": false,
    "isPending": true,
    "isError": false,
    "redirectUrl": "https://payment.unzer.com/v1/redirect/klarna/s-zlfTD9MuLNEC",
    "message": {
        "code": "COR.000.200.000",
        "merchant": "Transaction pending",
        "customer": "Your payment is currently pending. Please contact us for more information."
    },
    "amount": "105.9500",
    "currency": "EUR",
    "returnUrl": "https://www.unzer.com/de/kassenloesungen/",
    "date": "2022-09-05 12:45:52",
    "resources": {
        "customerId": "s-cst-6c8fe4e63bf9",
        "paymentId": "s-pay-173",
        "basketId": "s-bsk-7e772dd4266b",
        "traceId": "58e301db625ca471f3c8b9b78863ecda",
        "typeId": "s-kla-gixitbjxdm5c"
    },
    "additionalTransactionData": {
        "termsAndConditionUrl": "https://www.unzer.com/de",
        "privacyPolicyUrl": "https://www.unzer.com/de"
    },
    "orderId": "order-1662381951790-517",
    "paymentReference": "",
    "processing": {
        "uniqueId": "cfc69e0e-9ca9-4ec2-99fa-d6de718eef58",
        "shortId": "3493.0801.6897",
        "traceId": "58e301db625ca471f3c8b9b78863ecda"
    }
}

Forward the customer to the external payment page

After authorization, implement the following flow:

  1. Redirect the customer to the redirectUrl returned in the authorize response.
  2. The customer is forwarded to the klarna hosted payment page.
  3. After a successful payment or abort on the klarna page, the customer is redirected to the returnUrl specified in the initial authorize call.

When you ship the goods, it’s important to charge the payment. To learn more about shipment and charge, go to Manage Klarna payments.

Step 3: Check status of the payment
server side

Once the transaction is done, you can fetch the payment details from the API, by using the resources.paymentId from the authorize response above to handle the payment according to its status, such as s-pay-403. Check all possible payment states here.

GET https://api.unzer.com/v1/payments/{payment_ID}

{
    "id": "s-pay-403",
    "state": {
        "id": 0,
        "name": "pending"
    },
    "amount": {
        "total": "105.9500",
        "charged": "0.0000",
        "canceled": "0.0000",
        "remaining": "105.9500"
    },
    "currency": "EUR",
    "orderId": "order-1662381951790-517",
    "invoiceId": "",
    "resources": {
        "customerId": "s-cst-6c8fe4e63bf9",
        "paymentId": "s-pay-173",
        "basketId": "s-bsk-7e772dd4266b",
        "traceId": "58e301db625ca471f3c8b9b78863ecda",
        "typeId": "s-kla-gixitbjxdm5c"
    },
    "transactions": [
        {
            "date": "2022-09-28 11:45:20",
            "type": "authorize",
            "status": "success",
            "url": "https://api.unzer.com/v1/payments/s-pay-403/authorize/s-aut-1",
            "amount": "105.9500",
            "additionalTransactionData": {
                    "termsAndConditionUrl": "https://www.merchant.com/terms.html",
                    "privacyPolicyUrl": "https://www.merchant.com/privacy-policy.html" 
            }
        }
    ]
}
$unzer    = new UnzerSDK\Unzer('s-priv-xxxxxxxxxx');
$payment  = $unzer->fetchPayment('s-pay-xxxxxxx');
Unzer unzer = new Unzer("s-priv-xxxxxxxxxx");
Payment payment = unzer.fetchPayment("s-pay-xxxxxxx");

Step 4: Display the payment result
client side

Use the information from the Check status of the payment step to display the payment result to your customer.
This can be the success or error page of your shop. If something went wrong, you can use the client message from the API response and show it to the customer.

Manage payment
server side

For more details on managing Klarna, such as refunding them, see Manage Klarna payments.

Notifications

We recommend subscribing to the payment event to receive notifications about any changes to the payment resource. As soon as the event is triggered you should fetch the payment and update the order status in your shop according to its status.

  {
    "event":"payment.pending",
    "publicKey":"s-pub-xxxxxxxxxx",
    "retrieveUrl":"https://api.unzer.com/v1/payments/s-pay-774",
    "paymentId":"s-pay-774"
  }

For more details on implementing webhooks to receive notifications, see Notifications page.

Error handling

All requests to the API can result in an error that should be handled. Refer to the Error handling guide to learn more about Unzer API (and other) errors and handling them.

Test & go live

You should always test your integration before going live. First perform test transactions using test data. Next, check against Integration checklist and Go-live checklist to make sure the integration is complete and you’re ready to go live.

See also