alt

Important information

Please be advised that there will be a scheduled downtime across our API network on November 05 and November 07, 2024. For more information, visit our platform status portal.:
- Scheduled maintenance on November 5, 2024
- Scheduled maintenance on November 7, 2024

Unzer

Accept Klarna with UI components

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

Overview

Using UI components v2 for Klarna, create a payment type resource that is later used to make the payment. 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.

Legacy integration

This page describes the most recent integration of the UI Components, introduced in Jan 2025. For the Legacy integration guide go here.

Before you begin

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

First, you need to initiate our UI components v2 library and add the needed payment type component to your payment page.

Initiate UI Components

Load the Unzer JS script

Include the Unzer JS script on your website. This will load all the Unzer custom UI components with unzer- prefixed. For example, <unzer-paylater-invoice>.

Make sure to always include the script directly from the Unzer domain https://static-v2.unzer.com.

<script
        type="module"
        src="https://static-v2.unzer.com/v2/ui-components/index.js"
></script>
icon info
Faster load time
To make your website load faster, import the unzer script at the bottom of your HTML document.
Make sure to import the script as type=“module”.
icon info
Content security policy
To learn which URLs must be added to the allowlist for Unzer UI components in your content security policy, please refer to Content security policy section.

It is a good practice to put your website in loading state until the Unzer script is loaded, and the UI components are ready to use.

    // Make sure initially your application is in loading state
    // until all Unzer components are loaded
    Promise.all([
        customElements.whenDefined("unzer-payment"),
        // Probably add any other Unzer components used here. For example:
        // customElements.whenDefined("unzer-paylater-invoice"),
    ]).then(() => {
        // Hide the loading state and proceed with next steps
    }).catch((error) => {
        // Handle any error that might occur during the 
        // loading process and initialization
    });

UI setup and configuration

To securely collect payment data from your customer, you need to add the <unzer-payment> component, inside which you insert the needed payment type components.

icon
We recommend putting your submit button inside the <unzer-checkout> element. This will provide automatic handling for enabling/disabling the submit button depending on the current status, and showing/hiding of brand icons.
<unzer-payment
        id="unzer-payment"
        publicKey="s-pub-xyz"
        locale="de-DE">
    <!-- ... Here you will need to add the Unzer payment type tag, so the form UI elements will be inserted -->
    <!--    e.g <unzer-paylater-invoice></unzer-paylater-invoice> -->
</unzer-payment>
<unzer-checkout id='unzer-checkout'>
    <button type="submit" id="yourPaymentButtonId">Pay</button>
</unzer-checkout>

Following parameters need to be passed.

ParameterTypeDescriptionDefault value
publicKey (required)StringThe merchant public key.-
localeStringThe used locale. For more information on supported locales, see Localization.Browser user defined locale.
initDataobjectA key/value object in JSON-format containing data to initialize the payment type. For more information, Check payment methods and their features.Empty object {}

Optional: Customize UI components

Our UI components v2 are provided with a default theme that contains base styles. You can easily customize these styles by overriding the following CSS variables.

Variable nameDescriptionAffected components
--unzer-fontReplaces all fonts with the given font. Users can define any font-face and provide the name of the custom font-face.typography
--unzer-text-colorThe font color use for typography.typography, icons
--unzer-brand-colorThe main color of the application.button, checkbox, radio, loader
--unzer-background-colorThe page background.
--unzer-link-colorThe color of links.link
--unzer-corner-radiusWhether controls will have rounded corners or not. Values can be either 0 or 1.button, tags, chips
--unzer-shadowsWhether shadows are enabled or not. Values can be either 0 or 1.button, card
<head>
    <style>
        :root {
            --unzer-font: SFMono;
            --unzer-brand-color: #ee1818;
            --unzer-text-color: #f19316;
            --unzer-background-color: #6a9472;
            --unzer-link-color: #1330ef;
            --unzer-corner-radius: 0;
            --unzer-shadows: 1
        }
    </style>
</head>

Add Klarna payment method

To add the Klarna payment method insert unzer-klarna in the unzer-payment container.

<unzer-payment 
    publicKey="s-pub-xxxxxxxxxx"
    locale="de-DE">
  <unzer-klarna></unzer-klarna>
<unzer-payment>

<unzer-checkout>
    <button type="submit" id="yourPaymentButtonId">Pay</button>
</unzer-checkout>
icon
We recommend putting your submit button inside the <unzer-checkout> element. This will provide automatic handling of the submit whenever the user clicks the submit button, and passing back the creation payload.

Create payment type and customer resources

After the submit button is clicked, the customer and payment data are automatically submitted. You will then need to query the unzer-checkout element and handle the response inside its onPaymentSubmit event listener.

The following code example shows how to read customer and payment data from the response.

    // Make sure that this code is executed after the elements are rendered
    const unzerCheckout = document.getElementById('unzer-checkout');
    unzerCheckout.onPaymentSubmit = (response) => {
        if (response.submitResponse && response.customerResponse) {
            if (response.customerResponse.success) {
                // Optional: Only in case a new customer is created in the frontend.
                const customerId = response.customerResponse.data.id;
            }

            if (response.submitResponse.success) {
                const paymentTypeId = response.submitResponse.data.id;
            }

            // Submit all IDs to your server-side integration to perform the payment transaction.
        }
    };

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",
    "shippingType": "equals-billing"
  }
}
$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"
        }
    ]
}
$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": true,
    "isPending": false,
    "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