Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions api/paymentmethods/klarna/klarna.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ public function getPayload($data)
return array_merge_recursive($this->payload, $data);
}

public function reserve($customVars = [])
{
$this->payload = $this->getPayload($customVars);

return $this->executeCustomPayAction('reserve');
}

public function pay($customVars = [])
{
$this->payload = $this->getPayload($customVars);
Expand Down
19 changes: 19 additions & 0 deletions controllers/front/request.php
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,7 @@ private function handleSuccessfulRequest($cartId, $customer)
$this->logger->logInfo('Request succeeded');

if ($this->checkout->isRedirectRequired()) {
$this->storeKlarnaDataRequestKey($response);
$this->setCartCookie($cartId);
$this->logger->logInfo('Redirecting ... ');
$this->checkout->doRedirect();
Expand Down Expand Up @@ -550,6 +551,24 @@ private function handleFailedRequest($cartId)
Tools::redirect($redirectUrl);
}

private function storeKlarnaDataRequestKey($response): void
{
$method = Tools::strtolower(trim((string) Tools::getValue('method', '')));
if ($method !== 'klarna') {
return;
}

$responseData = $response->getResponse();
$dataRequestKey = $responseData ? trim((string) $responseData->getTransactionKey()) : '';
if ($dataRequestKey === '') {
return;
}

$id_order = (int) $this->module->currentOrder;
$this->createTransactionMessage($id_order, 'Data Request Key: ' . $dataRequestKey);
$this->storeTransactionKeyOnOrderPayment($id_order, $dataRequestKey);
}

private function createTransactionMessage($orderId, $messageString)
{
$message = new Message();
Expand Down
5 changes: 5 additions & 0 deletions controllers/front/return.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/

use Buckaroo\PrestaShop\Src\Refund\KlarnaTransactionKey;
use Buckaroo\PrestaShop\Src\Repository\RawBuckarooFeeRepository;
use Buckaroo\PrestaShop\Src\Service\BuckarooGroupTransactionService;

Expand Down Expand Up @@ -163,6 +164,10 @@ public function initContent()
$new_status_code = (int) Buckaroo3::resolveStatusCode($response->status, $id_order);
$order = new Order($id_order);

if (KlarnaTransactionKey::isCapturePush($response)) {
KlarnaTransactionKey::storeCaptureKey($order, (string) $response->transactions);
}

// Validate that the resolved order state actually exists in this shop.
if (!$this->isValidOrderStateId($new_status_code)) {
$this->logger->logError(
Expand Down
4 changes: 2 additions & 2 deletions library/checkout/checkout.php
Original file line number Diff line number Diff line change
Expand Up @@ -418,15 +418,15 @@ protected function prepareProductArticles()
}

/**
* Get product image URL if method is "afterpay"
* Get product image URL if method is "afterpay" or "klarna"
*
* @param array $product
*
* @return string|null
*/
private function getProductImgUrl($product)
{
if (Tools::getValue('method') !== "afterpay") {
if (!in_array(Tools::getValue('method'), ['afterpay', 'klarna'], true)) {
return null;
}

Expand Down
50 changes: 45 additions & 5 deletions library/checkout/klarnacheckout.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ final public function setCheckout()
$this->customVars = [
'operatingCountry' => Tools::strtoupper($country->iso_code),
'billing' => $this->getBillingAddress(),
'articles' => $this->getArticles(),
'articles' => $this->prepareKlarnaArticles($this->getArticles()),
'shipping' => $this->getShippingAddress(),
];
}
Expand All @@ -57,12 +57,12 @@ protected function getAddress(array $address): array
$address_components = $this->getAddressComponents($address['address1']); // phpcs:ignore
$address = array_merge($address, $address_components);

return [
$phone = !empty($address['phone_mobile']) ? $address['phone_mobile'] : ($address['phone'] ?? '');

$payload = [
'recipient' => [
'firstName' => $address['firstname'],
'lastName' => $address['lastname'],
'gender' => Tools::getValue('bpe_klarna_invoice_person_gender') === '1' ? 'male' : 'female',
'category' => 'B2C',
],
'address' => [
'street' => $address['street'],
Expand All @@ -74,6 +74,14 @@ protected function getAddress(array $address): array
],
'email' => $this->customer->email,
];

if (!empty($phone)) {
$payload['phone'] = [
'mobile' => $phone,
];
}

return $payload;
}

public function getShippingAddress()
Expand All @@ -96,11 +104,43 @@ public function isVerifyRequired()

public function startPayment()
{
$this->payment_response = $this->payment_request->pay($this->customVars);
$this->payment_response = $this->payment_request->reserve($this->customVars);
}

protected function initialize()
{
$this->payment_request = PaymentRequestFactory::create(PaymentRequestFactory::REQUEST_TYPE_KLARNA);
}

protected function prepareKlarnaArticles(array $articles): array
{
foreach ($articles as $key => $article) {
if (empty($article['type'])) {
$articles[$key]['type'] = $this->resolveKlarnaArticleType($article);
}
}

return $articles;
}

protected function resolveKlarnaArticleType(array $article): string
{
$identifier = isset($article['identifier']) ? (string) $article['identifier'] : '';
$price = isset($article['price']) ? (float) $article['price'] : 0.0;
$description = isset($article['description']) ? Tools::strtolower((string) $article['description']) : '';

if ($identifier === 'shipping' || $description === 'shipping costs') {
return 'shipping_fee';
}

if ($price < 0 || $description === 'discount') {
return 'discount';
}

if (in_array($identifier, ['0', 'buckaroo_fee'], true) || in_array($description, ['wrapping', 'buckaroo_fee'], true)) {
return 'surcharge';
}

return 'physical';
}
}
69 changes: 69 additions & 0 deletions src/Refund/KlarnaTransactionKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php
/**
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* It is available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade this file
*
* @author Buckaroo.nl <plugins@buckaroo.nl>
* @copyright Copyright (c) Buckaroo B.V.
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/

namespace Buckaroo\PrestaShop\Src\Refund;

if (!defined('_PS_VERSION_')) {
exit;
}

class KlarnaTransactionKey
{
/**
* Klarna Pay (capture) transaction type. Refunds must use this key, not the Reserve data request key.
*/
public static function isCapturePush($response): bool
{
$method = \Tools::strtolower((string) ($response->payment_method ?? ''));
if (strpos($method, 'klarna') === false) {
return false;
}

if (!empty($response->brq_relatedtransaction_refund)) {
return false;
}

return strtoupper((string) ($response->brq_transaction_type ?? '')) === 'C339'
&& $response->hasSucceeded()
&& trim((string) ($response->transactions ?? '')) !== '';
}

public static function storeCaptureKey(\Order $order, string $transactionKey): void
{
$transactionKey = trim($transactionKey);
if ($transactionKey === '' || !\Validate::isLoadedObject($order)) {
return;
}

$payments = \OrderPayment::getByOrderReference($order->reference);
if (!is_array($payments)) {
$payments = [];
}

foreach ($payments as $payment) {
if ((float) $payment->amount <= 0) {
continue;
}

if ((string) $payment->transaction_id !== $transactionKey) {
$payment->transaction_id = $transactionKey;
$payment->update();
}
break;
}
}
}
15 changes: 0 additions & 15 deletions views/templates/hook/payment_klarna.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,4 @@
*}
<section class="additional-information">
<input type="hidden" name="buckarooKey" value="klarna">
<form id="booIdealForm" action="{$link->getModuleLink('buckaroo3', 'request', ['method' => 'klarna'])|escape:'quotes':'UTF-8'}" method="post">
<div class="row row-padding">
<div class="col-xs-5">
<label class="required">{l s='Please select gender:' mod='buckaroo3'}</label>
</div>
<div class="col-xs-7">
<select name="bpe_klarna_person_gender"
id="bpe_klarna_person_gender"
class="required-entry form-control bk-form-control-large mb-2">
<option value="1" selected="selected" >{l s='He/him' mod='buckaroo3'}</option>
<option value="2">{l s='She/her' mod='buckaroo3'}</option>
</select>
</div>
</div>
</form>
</section>
Loading