Giter VIP home page Giter VIP logo

kco_rest_php's Introduction

[DEPRECATED] Official Klarna REST PHP SDK

Packagist Version Build Status Coverage Status

SDK Deprecation Warning and Sunsetting

Dear community, the SDK you are currently looking at is now deprecated. These are details related to sunsetting:

  • We intend to archive this repo on June 1 2020 (01/06/20)
  • Until November 1 2020 (01/11/20) high severity security issues found within the latest published version will be fixed. All support will cease after this date.
  • No new builds will follow effective April 20 (20/04/2020) apart from the fixes mentioned above.

Workarounds

We are making Klarna REST API definition files available in Swagger / OAS v2 format, under the Klarna API Reference section on the Klarna Developer Portal. These will be regularly updated as the APIs evolve. You can use tools like https://swagger.io/tools/swagger-codegen/ to generate your own SDKs, client libraries, etc.

Shop now. Pay later.

Shop at your favorite stores today and experience the freedom to pay later with Klarna.

Getting started

SDK covers all of Klarna API: https://developers.klarna.com/api/

Prerequisites

API Credentials

Before getting a production account you can get a playground one. Register here to be able to test your SDK integration before go live:

PHP SDK Installation and Usage

Install via Composer

To install the PHP SDK from the Central Composer repository use composer:

composer require klarna/kco_rest

Highly recommended to use version tag when installing SDK.

composer require klarna/kco_rest:1.2.3.4

Detailed information about the PHP SDK package and a list of available versions can be found here: https://packagist.org/packages/klarna/kco_rest

Include the SDK into your PHP file using the Composer autoloader:

<?php

require('vendor/autoload.php');

Manual installation

To install the PHP SDK manually you need to clone the repo to any folder on your machine:

git clone [email protected]:klarna/kco_rest_php.git /path/to/some/folder/kco_rest_php

Include the SDK into your PHP file using the SDK autoloader:

<?php

require('/path/to/some/folder/kco_rest_php/src/autoload.php');

⚠️Warning: Using manually installed SDK requires you to use the CURLTransport instance to send HTTP requests.

Read more about How to use HTTP Transport

Documentation and Examples

Klarna API documentation: https://developers.klarna.com/api/
SDK References: https://klarna.github.io/kco_rest_php/

Example files can be found in the docs/ directory.
Additional documentation can be found at https://developers.klarna.com.

Logging and Debugging

PHP SDK logs information to STDOUT/STDERR. To enable debug mode, set DEBUG_SDK environment variable:

$ DEBUG_SDK=true php <your_program.php>

or

$ export DEBUG_SDK=1
$ php <your_program.php>

Another way to enable Debugging Mode is define the DEBUG_SDK inside your script:

<?php
// some code here
define('DEBUG_SDK', true);
// some code here

Be aware, the SDK just checks if the DEBUG_SDK is defined! It means you will see the debug information by using define('DEBUG_SDK', false); or export DEBUG_SDK=no

More information about the DEBUG_SDK flag can be found here: #32

The output will look like:

DEBUG MODE: Request
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    GET : https://api.playground.klarna.com/customer-token/v1/tokens/TOKEN
Headers : {"User-Agent":["Library\/Klarna.kco_rest_php_3.1.0 (Guzzle\/6.3.3; curl\/7.54.0) OS\/Darwin_17.5.0 Language\/PHP_5.6.37"]}
   Body :

DEBUG MODE: Response
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Headers : {"Content-Type":["application\/json"],"Date":["Wed, 15 Aug 2018 15:55:53 GMT"],"Klarna-Correlation-Id":["ABC-123"],"Server":["openresty"],"Content-Length":["62"],"Connection":["keep-alive"]}
   Body : {
     "status" : "ACTIVE",
     "payment_method_type" : "INVOICE"
   }

Questions and feedback

If you have any questions concerning this product or the implementation, please create an issue: https://github.com/klarna/kco_rest_php/issues/new/choose

Use an official Klarna Contact us form (https://klarna.com) if you have a question about the integration.

How to contribute

At Klarna, we strive toward achieving the highest possible quality for our products. Therefore, we require you to follow these guidelines if you wish to contribute.

To contribute, the following criteria needs to be fulfilled:

  • Description regarding what has been changed and why
  • Pull requests should implement a boxed change
  • All code and documentation must follow the PSR-2 standard
  • New features and bug fixes must have accompanying unit tests:
    • Positive tests
    • Negative tests
    • Boundary tests (if possible)
    • No less than 90% decision coverage
  • All tests should pass

License

Klarna Checkout REST PHP SDK is licensed under Apache License, Version 2.0

kco_rest_php's People

Contributors

0x20h avatar alexions avatar amirrsyd avatar backendtea avatar dcolt avatar freethan avatar joakimlofgren avatar kasperfranz avatar keis avatar mitemitreski avatar mpesari avatar oradwell avatar sigismund avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kco_rest_php's Issues

DEBUG_SDK checking if defined, not the defined value

Describe the bug
We're implementing the Klarna Checkout SDK for one of our customer projects and noticed that we were repeatedly getting a lot of debug information through the requests even though we had defined DEBUG_SDK as false. When we went into the code we could out why. You're correctly using getenv to check if the value exists and get the value, but you're then only checking if the constant is actually defined, not it's value.

The issue is at this line:

$debug = getenv('DEBUG_SDK') || defined('DEBUG_SDK');

Which service do you use
Klarna Checkout

To Reproduce
Steps to reproduce the behavior:

  1. Define the DEBUG_SDK constant as false as below:
    <?php define('DEBUG_SDK', false); ?>
  2. Make a request to the API, for instance create a new Order.

Expected behavior
Klarna SDK debug output should not show.

Discount % applied to discounts on pre-4.0 after 4.0 was released.

Seems like you changed something in the API, because right now discounts are getting discount applied to discounts.

Example of the issue:

image 2018-10-31 at 11 40 57 am

Previously before you released 4.0 it worked as expected:

image 2018-10-31 at 11 42 26 am

Code used:

image 2018-10-31 at 11 40 04 am

You cannot resonably expect us to rewrite our integrations the same day you release 4.0.

Missing expected return from distrubuting link

Describe the bug
Throws exception on 204 return when distributing link.

Which service do you use
Example: Klarna HostedPaymentPage

To Reproduce
Steps to reproduce the behavior:

  1. Create a Payment Session in Test envirorment
  2. Create a HPP for that Payment session
  3. Use HPP distributeLink
  4. See error (link still gets sent)

Expected behavior
Silent return with no throw.

Additional context
Issue gets fixed by adding 204 to the expected statuses in src/Klarna/Rest/HostedPaymentPage/Session.php line 132

6.3 release guzzle / php 7.0.20

Hi guys, this repo is very old... It uses old guzzle too
I want to use the newest versions, because our production environment is the newest php.

Can I even start developing with this?? or do i need to search for other payment providers.

Some help would be appreciated..

Payments Session ID is reset after fetch()

Describe the bug
I'm not sure whether this is a bug or an undocumented(?) feature.

I'm trying to use an existing Payments Session if possible. I accidentally ended up creating a new session every time, because I did some checks on $session->getId(). Use case here is e-commerce checkout page.

Which service do you use
Klarna Payments

To Reproduce
Steps to reproduce the behavior:

  1. Customer comes to checkout page for the first time: create a new session, save id somewhere
$session = new \Klarna\Rest\Payments\Sessions($connector, null);
$session->create($data);
$session_id = $session->getId(); // "foo-bar-123"
  1. User goes away and comes back to checkout page: update existing session
$session = new \Klarna\Rest\Payments\Sessions($connector, $session_id);
var_dump($session->getId()); // "foo-bar-123"

$session->update($data);
var_dump($session->getId()); // "foo-bar-123"

// get payment_method_categories etc. because they are not populated by update()
$session->fetch();
var_dump($session->getId()); // NULL

Expected behavior
I would expect the session ID not change to null. It happens in Resource::fetch() because the API returns data that doesn't include the ID. Local workaround was to store the ID before exchangeArray() and apply it back afterwards.

$this->exchangeArray($data);

Additional context
klarna/kco_rest v4.1.5

401 Unauthorized for Checkout API

Describe the bug
I'm running a test on the checkout https://api.playground.klarna.com/checkout/v3/orders API using the data provided here https://developers.klarna.com/documentation/klarna-checkout/integration-guide/render-the-checkout/

This is what the modified json playload looks like

{ "purchase_country": "se", "purchase_currency": "sek", "locale": "en-GB", "billing_address": { "given_name": "Testperson-se", "family_name": "Approved", "email": "[email protected]", "street_address": "Stårgatan 1", "postal_code": "12345", "city": "Ankeborg", "phone": "+46765260000", "country": "se" }, "order_amount": 503341, "order_tax_amount": 100668, "order_lines": [ { "type": "physical", "reference": "19-402-SWE", "name": "Camera Travel Set", "quantity": 1, "quantity_unit": "pcs", "unit_price": 603341, "tax_rate": 2500, "total_amount": 503341, "total_discount_amount": 100000, "total_tax_amount": 100668, "image_url": "https://www.verkkovaraani.fi/wp-content/uploads/2019/05/verkkovaraani-logo-lrg-300x82.png" } ], "merchant_urls": { "terms": "https://www.verkkovaraani.fi", "checkout": "https://www.verkkovaraani.fi", "confirmation": "https://www.verkkovaraani.fi", "push": "https://www.verkkovaraani.fi" }, "shipping_options": [ { "id": "free_shipping", "name": "Free Shipping", "description": "Delivers in 5-7 days", "price": 0, "tax_amount": 0, "tax_rate": 0, "preselected": true, "shipping_method": "Home" }, { "id": "pick_up_store", "name": "Pick up at closest store", "price": 399, "tax_amount": 0, "tax_rate": 0, "preselected": false, "shipping_method": "PickUpStore" } ] }

Which service do you use
Klarna Checkout

To Reproduce
Steps to reproduce the behavior:

  1. I have used the PHP SDK and Postman, both gave me the same result

Expected behavior
As described in the docs

Additional context
The weird thing is that i can see the log in my account. and when i add the attachment node to the payload. It returns a validation error.

Settlements API Unexpected Header

Executing

$payout = new \Klarna\Rest\Settlements\Payouts($connector);
$payout->page($offset, $size, $start_date, $end_date, $currency_code);

we get

PHP Fatal error: Uncaught exception 'RuntimeException' with message 'Unexpected Content-Type header received: application/json; charset=utf-8' in ../vendor/klarna/kco_rest/src/Klarna/Rest/Transport/ResponseValidator.php:105

ResponseValidator is checking against 'application/json' without charset information

Create session for klarna payment integration issue

We are unable to get the create session reponse during klarna payment integration , because of the incorrect value generation of authorization parameter in create session step. The authorization parameter calculation is basis on : base64(hex(sha256 (request_payload + shared_secret))) . We need clear describition about each and every variable used for authorization key generation .

What does the base64 means ? Is it base64_encode or base64_decode?
What you mean by hex() , sha256() and request_payload?

Customer token not found - HPP

Apologies if this is the wrong place for this, wasn't sure if you had a ticket system or anything

Describe the bug
I've got as far as the response from the hosted payment page which gives me a token in the url, example: token=55a5605d-7a11-2d2b-a716-a16ec1a6e327

I then use the Klarna\Rest\CustomerToken\Tokens class to attempt to read the token I've received but it just gives me an error every time

TOKEN_NOT_FOUND: Customer token not found (#e11340df-6405-43fa-8110-f8ec6d1086cb)

Which service do you use
Hosted Payment Page, Playground environment

To Reproduce
Steps to reproduce the behavior:
Basically this but with the token 55a5605d-7a11-2d2b-a716-a16ec1a6e327 (and my merchant/secret)
https://github.com/klarna/kco_rest_php/blob/v4.x/docs/examples/CustomerTokenAPI/Tokens/read_token_details.php

Expected behavior
Fetch the token details so I can check that it's a valid token and go on to create the order

Additional context
Playground environment, tried various tokens not just 1

Following this: https://developers.klarna.com/documentation/hpp/guides/kp-integration/

So stuck on step 5 due to the token not found error

How do i install this

Hi, im new to this and I want to install klarna checkout on my site, but the module says I need to have kco_rest?

Can anyone help me?

Old version of Guzzle

Your version of guzzle is too old.

We've tried to keep the old version but it prevents us from updating/installing anything else.

Upgrade v2 to v3

Where's the upgrade guide from v2 to v3?

And how do you use it without Composer? It doesn't even work with Composer.

Why do you over complicate things when not needed?

Placing order using examples doesn't bounce browser to Klarna

I'm trying to work with the a direct integration of the Klarna Payments API. I've been following the integration guide and I'm up to the Place Order stage (https://developers.klarna.com/documentation/klarna-payments/integration-guide/place-order). I'm using their example script to place an order (https://github.com/klarna/kco_rest_php/blob/v4.x/docs/examples/PaymentsAPI/Orders/create_order.php).

Upon redirecting the user, the user is sent straight to the confirmation page rather than a Klarna page to enter their billing details (as described in the integration guide above).

I post the authorization_token to their example script using a form. Their example script responds with an array containing a redirect_url, which I redirect the script to. However, this leads to the order_confirmation page that is passed as an argument to order->create().

// The form I'm using to post to their example script:

form action="klarna_order.php" method="post"
input id="authorization_token" name="authorization_token" type="hidden"
input type="submit" value="Submit"
/form

// The part where the order is created and I redirect the page in the example // script:

try {
$order = new Klarna\Rest\Payments\Orders($connector, $authorizationToken);
$data = $order->create($data);
print_r($data);
header('Location: '.$data['redirect_url']);
die();
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage() . "\n";
}

The output of the klarna_order.php file (their example file) is this, which looks right:

'Array ( [order_id] => 1caa1e86-8e71-7bfa-bdd2-ff718365f1af [redirect_url] => https://klarna-payments-eu.playground.klarna.com/v1/sessions/dfa44305-aa56-7861-ac51-fee7c42ce986/redirect [fraud_status] => ACCEPTED [authorized_payment_method] => Array ( [type] => invoice ) )'

If I redirect them to the redirect_url in the response, as their guide says, the browser goes straight to the order_confirmation page instead of a Klarna page where the customer can enter their billing details.

Has this always been for Klarna v3?

There is a Klarna Checkout module using this SDK, released in 2016, by Klarna for Opencart here: https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=27099

I have asked Klarna customer service whether that module is for Klarna v2 or v3, but they can't anwer that question.

Now that I see that this SDK is for Klarna v3, I would assume that module is as well. But has this SDK always been for Klarna v3?

I hope someone here can answer whether that module was/is for v2 or v3?

"getenv" function is not working !

I am using this library in laravel framewok 5.5. The problem is, I have set "DEBUG_SDK" as false in my .env (environment) file. but it is not reflecting in this library file (klarna/kco_rest/src/Klarna/Rest/Resource.php). because of getenv function is not working.

Note: Currently, env() function is used instead of getenv().

PSR4 autoload definition is defined as fallback directory

Describe the bug
Current definition of autoload in composer.json ("autoload":{"psr-4":{"":"src/"}}) causes composer to use this as a fallback directory for all classes to look up (see https://getcomposer.org/doc/04-schema.md#psr-4).

Expected behavior
Defining the Klarna namespace according to the correct directory, as all classes are namespaced with Klarna/, this config would work find and would prevent composer from using the /klarna/kco_rest/src directory as a fallback directory: "autoload":{"psr-4":{"Klarna\\":"src/Klarna/"}}

401 Authorization error

Describe the bug
401 Authorization error

Which service do you use
Klarna Checkout

To Reproduce
The bug occurs even with the latest 4.1.2 version.

  1. Just use the 4.1.2 package
  2. Use the create_checkout.php example in the docs folder
  3. Just replace the Merchant ID and shared secret. even for valid credentials, 401 occurs

Is this still in development?

The last commit dates back to Dec 2015.
Is this the official KCO package that should be used?
Since your guzzle package requirement is older than Gandalf it seems to be somewhat archived, but maybe that's not the case?

Do you plan on any new release soon for this?

Caught exception: Response is missing a Content-Type header

Klarna Checkout API is throwing error with valid code example.

This block of code seems to be causing the error. If you remove this block from the example below the checkout is rendering without errors:
"options" => [ "additional_checkbox" => [ "text" => "Please add me to the newsletter list, read more here link", "checked" => false, "required" => false ], ],

Error thrown:
Caught exception: Response is missing a Content-Type header

Reproduce with this full example.

$merchantId = '';
$sharedSecret = '';

$apiEndpoint = Klarna\Rest\Transport\ConnectorInterface::EU_TEST_BASE_URL;

// Create cURL HTTP Transport Connector
$connector = Klarna\Rest\Transport\CURLConnector::create($merchantId,$sharedSecret,$apiEndpoint);

$order = [
    "purchase_country" => "se",
    "purchase_currency" => "sek",
    "locale" => "sv-se",
    "order_amount" => 12750,
    "order_tax_amount" => 2550,

    "order_lines" => [
        [
            "type" => "physical",
            "reference" => "abc123",
            "name" => "Product Name",
            "quantity" => 1,
            "unit_price" => 10000,
            "tax_rate" => 2500,
            "total_amount" => 10000,
            "total_tax_amount" => 2000
        ],
        [
            "type" => "discount",
            "reference" => "discount50",
            "name" => "Discount 50%",
            "quantity" => 1,
            "unit_price" => -5000,
            "tax_rate" => 2500,
            "total_amount" => -5000,
            "total_tax_amount" => -1000
        ],
        [
            "type" => "shipping_fee",
            "reference" => "shipping",
            "name" => "Shipping",
            "quantity" => 1,
            "unit_price" => 7750,
            "tax_rate" => 2500,
            "total_amount" => 7750,
            "total_tax_amount" => 1550
        ],
    ],

    "options" => [
        "additional_checkbox" => [
            "text" => "Please add me to the newsletter list, read more here link",
            "checked" => false,
            "required" => false
        ],
    ],

    "merchant_urls" => [
        "terms" => "http://www.merchant.com/toc",
        "checkout" => "http://www.merchant.com/checkout?klarna_order_id={checkout.order.id}",
        "confirmation" => "http://www.merchant.com/thank-you?klarna_order_id={checkout.order.id}",
        "push" => "http://www.merchant.com/create_order?klarna_order_id={checkout.order.id}"
    ],

];

try {
    $checkout = new Klarna\Rest\Checkout\Order($connector);
    $checkout->create($order);

    // Store checkout order id
    $orderId = $checkout->getId();

    // Get some data if needed
    echo <<<ORDER
         OrderID: $checkout[order_id]
    Order status: $checkout[status]
    HTML snippet: $checkout[html_snippet]
ORDER;
} catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage() . "\n";
}

Dokumentationen använder reserverad miljövariabel i Windows - getenv('USERNAME')

I mycket exempel-kod under docs anges merchantId och sharedSecret så här:

$merchantId = getenv('USERNAME') ?: 'K123456_abcd12345';
$sharedSecret = getenv('PASSWORD') ?: 'sharedSecret';

Använder man PHP i Windows leder det dock till problem eftersom getenv('USERNAME') by default returnerar namnet på användaren som kör scriptet: https://stackoverflow.com/questions/12754437/get-windows-username-of-current-user-using-php

Kör man dessa kodsnuttar och ersätter med sina egna värden kommer de inte att användas och Klarna API kommer att returnera 401 Authorization Required.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.