alt

Important information

There was an update of Unzer TLS/SSL certificates. Learn more

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 https://static.unzer.com:

<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 js 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 (e.g. enable the `pay` button)
  } else {
    // run some code (e.g. 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 for completing 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"
  }
}

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 as well as 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"
        }
    ]
}
$unzer      = new UnzerSDK\Unzer('s-priv-xxxxxxxxxx');
$basketItem = (new UnzerSDK\Resources\EmbeddedResources\BasketItem())
                  ->setTitle('Notebook pro')
                  ->setSubTitle('basket item subtitle')
                  ->setBasketItemReferenceId('item-1')
                  ->setQuantity(1)
                  ->setTotalValueGross(2000)
                  ->setVat(19.0)
                  ->setType(UnzerSDK\Constants\BasketItemTypes::GOODS)
                  ->setUnit('pc');

$basket  = (new UnzerSDK\Resources\Basket())
    ->setTotalValueGross(2000)
    ->setCurrencyCode('EUR')
    ->setOrderId('O-12345-AB')
    ->setNode('basket note')
    ->addBasketItem($basketItem);

$unzer->createBasket($basket);
Currently not supported

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.

Parameter Type Description
amount (required) float The authorization amount
currency (required) string The authorization currency, in the ISO 4217 alpha-3 format
returnURL (required) string The return URL where the customer must be redirected after a charge transaction.
orderID(required) string This is used to send the order ID from your shop to the API
customerId (required) string The ID of the customers resource to be used
basketId (required) string The basket ID for the payment
typeId (required) string The ID of the payment type resource to be used
additionalTransactionData
termsAndConditionUrl (required) string The link to the terms and conditions URL of your webshop.
privacyPolicyUrl (required) string The link to the privacy policy for your webshop.
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"
    }
}
Currently not supported.

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/s-pay-xxxxxxx
{
    "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" 
            }
        }
    ]
}
Currently not supported
Currently not supported

Step 4: Display the payment result
client side

Use the information from the Check status of the payment step to show 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, 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