Klarna Payments

1.4k Views Asked by At

I try to integrate klarna payments for opencart.

I get an client_token from klarna, so the iframe is shown.

next step is to authorize the testdata.

unfortunately I get { "show_form": false, "approved": false }

back as result.

I send the following testscript:

                        <script>
                            try {
                                    Klarna.Payments.init({
                                      "client_token":"<?php echo $klarna_client_token ?>"
                                    })

                          } catch (e) {
                                // Fehler anzeigen
                                alert(e);
                            }

                                Klarna.Payments.load({
                                  container: '#klarna-payments-container',
                                  payment_method_category: 'pay_later'
                                }, function (res) {

                                    console.log(JSON.stringify(res, null, 4));

                                })



                                Klarna.Payments.authorize({
                                  payment_method_category: "pay_later"
                                }, {
                                  billing_address: {
                                    given_name: "Omer",
                                    family_name: "Heberstreit",
                                    email: "[email protected]",
                                    title: "Herr",
                                    street_address: "Hermannstraße 64",
                                    street_address2: "",
                                    postal_code: "53225",
                                    city: "Bonn",
                                    phone: "+491522113356",
                                    country: "DE"
                                  },
                                  order_amount: 10,
                                  order_tax_amount: 0,
                                  order_lines: [{
                                    type: "physical",
                                    reference: "19-402",
                                    name: "Battery Power Pack",
                                    quantity: 1,
                                    unit_price: 10,
                                    tax_rate: 0,
                                    total_amount: 10,
                                    total_discount_amount: 0,
                                    total_tax_amount: 0,
                                    product_url: "https://www.estore.com/products/f2a8d7e34",
                                    image_url: "https://www.exampleobjects.com/logo.png"
                                  }],
                                  customer: {
                                    date_of_birth: "1970-01-01",
                                  }
                                }, function(res2) {


                                    console.log(JSON.stringify(res2, null, 4));

                                })


                        </script>


                        <div id="klarna-payments-container"></div>

It should work, because its official testdata from klarna. did someone know, why it does not work?

greetings

2

There are 2 best solutions below

0
On
try {
                                    Klarna.Payments.init({
                                      "client_token":"<?php echo $klarna_client_token ?>"
                                    })

                          } catch (e) {
                                // Fehler anzeigen
                                alert(e);
                            }

                                Klarna.Payments.load({
                                  container: '#klarna-payments-container',
                                  payment_method_category: 'pay_later'
                                }, function (res) {

                                    console.log(JSON.stringify(res, null, 4));

                                })

The above can be changed to:

//The following method initializes the Klarna Payments JS library
    window.klarnaAsyncCallback = function () {
        Klarna.Payments.init({ 
            client_token: '<?php echo $klarna_client_token ?>'
        });
        console.log("Payments initialized");
    //The following method loads the payment_method_category in the container with the id of 'klarna_container'
        Klarna.Payments.load({
        container: '#klarna_container',
            payment_method_category: 'pay_later'
            
        }, function (res) {
               console.log("Load function called")
                console.debug(res);
        });
    };

The init and load functions are to be called in klarnaAsyncCallback. I have noticed that the authorize function always return { "show_form": false, "approved": false } and the popup does not appear if it is called inside the init function or not inside an event.

/*The following is the authorize function, which triggers Klarna to perform a risk assessment of the purchase 
  The successful response of this risk assessment is an authorization token, which in this example is logged in the console
*/
  

    $(function(){
        $("button.authorize").on('click', function(){
    Klarna.Payments.authorize({
                                      payment_method_category: "pay_later"
                                    }, {
                                      billing_address: {
                                        given_name: "Omer",
                                        family_name: "Heberstreit",
                                        email: "[email protected]",
                                        title: "Herr",
                                        street_address: "Hermannstraße 64",
                                        street_address2: "",
                                        postal_code: "53225",
                                        city: "Bonn",
                                        phone: "+491522113356",
                                        country: "DE"
                                      },
                                      order_amount: 10,
                                      order_tax_amount: 0,
                                      order_lines: [{
                                        type: "physical",
                                        reference: "19-402",
                                        name: "Battery Power Pack",
                                        quantity: 1,
                                        unit_price: 10,
                                        tax_rate: 0,
                                        total_amount: 10,
                                        total_discount_amount: 0,
                                        total_tax_amount: 0,
                                        product_url: "https://www.estore.com/products/f2a8d7e34",
                                        image_url: "https://www.exampleobjects.com/logo.png"
                                      }],
                                      customer: {
                                        date_of_birth: "1970-01-01",
                                      }
                                    }, function(res2) {
    
    
                                        console.log(JSON.stringify(res2, null, 4));
    
                                    })
        })
      })

For Example, the authorize function can be triggered by a button click and it appears to create the popup and return authorization token after the flow.

Something like this should help:

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://x.klarnacdn.net/kp/lib/v1/api.js" async></script>
</head>

<body>



    <script type="text/javascript">
        //The following method initializes the Klarna Payments JS library
        window.klarnaAsyncCallback = function() {
            Klarna.Payments.init({
                client_token: '< client-token >'
            });
            console.log("Payments initialized");
            //The following method loads the payment_method_category in the container with the id of 'klarna_container'
            Klarna.Payments.load({
                container: '#klarna_container',
                payment_method_category: '< pay_later | pay_over_time >'

            }, function(res) {
                console.log("Load function called")
                console.debug(res);
            });
            //Multiple widgets can be loaded by calling the load function again
            /*  Klarna.Payments.load({
                 container: '#klarna_container',
                 payment_method_category: '< pay_later | pay_over_time >'

             }, function(res) {
                 console.log("Load function called")
                 console.debug(res);
             }); */
        };



        /*The following is the authorize function, which triggers Klarna to perform a risk assessment of the purchase 
          The successful response of this risk assessment is an authorization token, which in this example is logged in the console
        */
        $(function() {
            $("button.authorize").on('click', function() {
                Klarna.Payments.authorize({
                    payment_method_category: "< pay_later | pay_over_time >"
                }, {
                    purchase_country: "GB",
                    purchase_currency: "GBP",
                    locale: "en-GB",
                    billing_address: {
                        given_name: "Test",
                        family_name: "Person-uk",
                        email: "[email protected]",
                        street_address: "13 New Burlington St",
                        street_address2: "Apt 214",
                        postal_code: "W13 3BG",
                        city: "London",
                        region: "",
                        phone: "01895808221",
                        country: "GB"
                    },
                    order_amount: 1000,
                    order_tax_amount: 0,
                    order_lines: [{
                        type: "physical",
                        reference: "19-402",
                        name: "Battery Power Pack",
                        quantity: 1,
                        unit_price: 1000,
                        tax_rate: 0,
                        total_amount: 1000,
                        total_discount_amount: 0,
                        total_tax_amount: 0,
                        product_url: "https://www.estore.com/products/f2a8d7e34",
                        image_url: "https://www.exampleobjects.com/logo.png"
                    }],
                    //     customer: {
                    //     date_of_birth: "1970-01-01",
                    // },
                }, function(res) {
                    console.log("Response from the authorize call:")
                    console.log(res)
                })
            })
        })
    </script>


    <div style="width: 500px; margin: auto; padding-top: 150px; padding-bottom: 30px;">
        <img src="https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg" style="width: 500px; margin: auto;">
    </div>

    <!--Klarna container-->
    <div id="klarna_container" style="width: 500px; margin: auto;"></div>
    <div style="width: 500px; margin: auto;">
        <!--Button to trigger authorize call-->
        <button class="authorize" style="width: 500px; height: 50px; margin: auto;">Buy Now</button>
    </div>
    </script>
</body>

</html>
1
On

I Successfully Integrated the Klarna Payment Method in React.JS & Next.JS 14

Resolved the Initialization and 'On' Function Issue in Klarna, Successfully Implemented in a Next.js App.

"use client";
import React from "react";
import Script from "next/script";

export default function SortableTree() {
  return (
    <>
      <Script
        async
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"
      />
      <div id="klarna_container">
        <div>
          <button className="authorize">Buy Now</button>
        </div>
      </div>
      <Script async src="https://x.klarnacdn.net/kp/lib/v1/api.js" />
      <Script async id="klarna_container" type="text/javascript">
        {`  
        const script = document.createElement('script');
        script.src = 'https://code.jquery.com/jquery-3.3.1.min.js'; // Use a CDN or your local copy
        script.async = true;
        script.onload = () => {
          // jQuery is now loaded
          $(function ($) {
            window.klarnaAsyncCallback = function () {
              Klarna.Payments.init({
                client_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjgyMzA1ZWJjLWI4MTEtMzYzNy1hYTRjLTY2ZWNhMTg3NGYzZCJ9.eyJzZXNzaW9uX2lkIjoiZTdiMDgzOTAtYWY4OS01MDRiLWFkZTYtNDYzNTQ4YWI1NTgyIiwiYmFzZV91cmwiOiJodHRwczovL2pzLnBsYXlncm91bmQua2xhcm5hLmNvbS9uYS9rcCIsImRlc2lnbiI6ImtsYXJuYSIsImxhbmd1YWdlIjoiZW4iLCJwdXJjaGFzZV9jb3VudHJ5IjoiVVMiLCJlbnZpcm9ubWVudCI6InBsYXlncm91bmQiLCJtZXJjaGFudF9uYW1lIjoiWW91ciBidXNpbmVzcyBuYW1lIiwic2Vzc2lvbl90eXBlIjoiUEFZTUVOVFMiLCJjbGllbnRfZXZlbnRfYmFzZV91cmwiOiJodHRwczovL25hLnBsYXlncm91bmQua2xhcm5hZXZ0LmNvbSIsInNjaGVtZSI6dHJ1ZSwiZXhwZXJ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TMWKM6yfQb3UUI-k2dr2aKekFq8nSeYhOl6TZUrUlqHhTc-XSwHXT26cGNBv2OibXOdSn5KZGE0n0b3kpgs46Iyj9f329Yoo1MogMNZHOqgWTAgCapa3SAj-B1DSFJdwwEXkRJXRHEpLsqpKjbiRzJL3VVKkx-mO-dWDPnfjyL74TMTFB7fpQkbm3nKFLNa5qjFrq9qYsCN-ycJur6I7Pq_U7Xvb2_wP6K6NqgWa0nOCy3wXZlw',
              });
    
              Klarna.Payments.load({
                container: '#klarna_container',
                payment_method_category: 'pay_over_time',
              }, function (res) {
                console.log("Load function called");
                console.debug(res);
              });
    
              // Additional Klarna.Payments.load for multiple widgets
    
              $("button.authorize").on('click', function () {
                Klarna.Payments.authorize({
                  payment_method_category: "pay_over_time"
                }, {
                  purchase_country: "DE",
                  purchase_currency: "EURGBP",
                  locale: "en-GB",
                  // ... (rest of your authorize configuration)
                }, function (res) {
                  console.log("Response from the authorize call:");
                  console.log(res);
                })
              });
            };
    
            // Call your klarnaAsyncCallback after jQuery is loaded
            window.klarnaAsyncCallback();
          });
        };
    
        document.head.appendChild(script);
        `}
      </Script>
    </>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>