Files
esun3d/app/code/Esun/OceanpaymentKlarna/Model/Gateway/ItemListBuilder.php
T
2026-09-15 10:35:56 +08:00

129 lines
3.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Gateway;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Model\Order;
class ItemListBuilder
{
public function build(Order $order): string
{
$items = $order->getAllVisibleItems();
if ($items === []) {
throw new LocalizedException(__('Klarna requires at least one order item.'));
}
$names = [];
$skus = [];
foreach ($items as $item) {
$names[] = (string)$item->getName();
$skus[] = (string)$item->getSku();
}
$shipping = max(0, $this->toCents((float)$order->getShippingAmount()));
$tax = max(0, $this->toCents((float)$order->getTaxAmount()));
$grandTotal = $this->toCents((float)$order->getGrandTotal());
$goods = $grandTotal - $shipping - $tax;
if ($goods <= 0) {
throw new LocalizedException(__('Klarna requires a positive merchandise amount.'));
}
// Match Oceanpayment's Magento Klarna payload: one net merchandise
// node plus fixed discount, shipping and tax nodes. This avoids sending
// zero-value gifts or synthetic overflow products to Klarna.
$nodes = [
$this->node(
'1',
implode(';', $names),
implode(';', $skus),
$goods,
'1',
$goods,
number_format($tax / $goods, 2, '.', ''),
$tax
),
$this->node('3', 'discount', 'discount', 0, '0', 0, '0', 0),
$this->node('4', 'shipping_fee', 'shipping', $shipping, '1', $shipping, '0', 0),
$this->node('5', 'sales_tax', 'tax', $tax, '1', $tax, '0', $tax),
];
$this->assertTotal($order, $nodes);
return $this->encode($nodes);
}
private function node(
string $type,
string $title,
string $sku,
int $price,
string $quantity,
int $total,
string $taxRate,
int $taxPrice
): array {
return [
'type' => $type,
'title' => $this->clean($title, 100),
'sku' => $this->clean($sku, 100),
'price' => $this->money($price),
'quantity' => $quantity,
'total_amount' => $this->money($total),
'taxRate' => $taxRate,
'taxPrice' => $this->money($taxPrice),
'image_url' => '',
'product_url' => '',
'remark' => '',
'_cents' => $total,
];
}
private function assertTotal(Order $order, array $nodes): void
{
$total = 0;
foreach ($nodes as $node) {
$total += $node['type'] === '3' ? -$node['_cents'] : $node['_cents'];
}
if ($total !== $this->toCents((float)$order->getGrandTotal())) {
throw new LocalizedException(__('Klarna item total does not match the order total.'));
}
}
private function encode(array $nodes): string
{
$payload = [];
foreach ($nodes as $index => $node) {
unset($node['_cents']);
$payload[(string)$index] = $node;
}
$json = json_encode((object)$payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new LocalizedException(__('Unable to encode Klarna item data.'));
}
return $json;
}
private function clean(string $value, int $length): string
{
$value = preg_replace('/[<>\'"\x00-\x1F]/u', ' ', trim($value)) ?? '';
$value = preg_replace('/\s+/u', ' ', $value) ?? '';
return mb_substr($value !== '' ? $value : '-', 0, $length);
}
private function toCents(float $amount): int
{
return (int)round($amount * 100);
}
private function money(int $cents): string
{
return number_format($cents / 100, 2, '.', '');
}
}